Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

java - Loading JDBC Driver at Runtime

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

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

DriverManager.registerDriver(driver);

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...