Loading JDBC Driver at Runtime

前端 未结 3 1235
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 05:37

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

public class DriverLoader extends URLClassLoader {

    private DriverLoader(URL[] urls) {
        supe         


        
相关标签:
3条回答
  • 2021-01-19 05:54

    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.

    0 讨论(0)
  • 2021-01-19 06:01

    You should establish connection in a class loaded by your DriverLoader. So, load the connection establishment code using DriverLoader and then call JDBC from it.

    0 讨论(0)
  • 2021-01-19 06:15

    You need to add a Classpath reference in the manifest. Follow these simple steps:

    add a folder "lib" to your application

    place "mysql-connector-java-5.1.18-bin" in lib

    now open your "MANIFEST.MF" and go to tab "RUNTIME"

    on bottom right, you would see "classpath" ; click "Add"

    now add the folder lib [created in step 1] along with the jar file

    in this way, whenever a runtime EclipseApplication /OSGi Application is started this jar file is exported along too. So the connectivity would then be available there too.

    0 讨论(0)
提交回复
热议问题