Loading JDBC Driver at Runtime

ε祈祈猫儿з 提交于 2019-12-01 17:55:57

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!