在运行时加载JDBC驱动程序 [英] Loading JDBC Driver at Runtime

查看:182
本文介绍了在运行时加载JDBC驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码加载驱动程序类:

I'm using the following code to load a driver class:

public class DriverLoader extends URLClassLoader {

    private DriverLoader(URL[] urls) {
        super(urls);
        File driverFolder = new File("driver");
        File[] files = driverFolder.listFiles();
        for (File file : files) {
            try {
                addURL(file.toURI().toURL());
            } catch (MalformedURLException e) {
            }
        }
    }


    private static DriverLoader driverLoader;


    public static void load(String driverClassName) throws ClassNotFoundException {
        try {
            Class.forName(driverClassName);
        } catch (ClassNotFoundException ex) {
            if (driverLoader == null) {
                URL urls[] = {};
                driverLoader = new DriverLoader(urls);
            }
            driverLoader.loadClass(driverClassName);
        }
    }
}

虽然课程加载很好我无论我尝试使用哪种驱动程序,都无法建立数据库连接(找不到合适的驱动程序...)。

Although the class loads fine I can't establish a Database connection (No suitable driver found for ...) no matter which driver I try.

我认为这是因为我没有加载使用Class.forName的驱动程序类(由于我使用自己的ClassLoader,因此无效)。我该如何解决这个问题?

I assume this is because I'm not loading the driver class using Class.forName (which wouldn't work since I'm using my own ClassLoader). How can I fix this?

推荐答案

您需要先创建一个驱动程序类的实例才能连接:

You need to create an instance of the driver class before you can connect:

Class drvClass = driverLoader.loadClass(driverClassName);
Driver driver = drvClass.newInstance();

获得实例后,您可以使用该实例进行连接:

Once you have the instance you can either use that instance to connect:

Properties props = new Properties();
props.put("user", "your_db_username");
props.put("password", "your_db_password");
Connection con = driver.connect("jdbc:postgresql:...", props);

作为替代方案,如果您想继续使用DriverManager,您必须手动向DriverManager注册驱动程序:

As an alternative, if you want to keep using DriverManager you must register the driver with the DriverManager manually:

DriverManager.registerDriver(driver);

然后你应该可以使用DriverManager来建立连接。

Then you should be able to use the DriverManager to establis a connection.

如果我没记错,如果驱动程序本身没有与DriverManager相同的类加载器加载,则DriverManager拒绝连接时出现问题。如果是(仍然),则需要直接使用Driver.connect()。

If I recall it correctly there was a problem with the DriverManager refusing to connect if the driver itself was not loaded by the same classloader as the DriverManager. If that (still) is the case, you need to use Driver.connect() directly.

这篇关于在运行时加载JDBC驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆