动态加载JDBC驱动程序 [英] Dynamically load the JDBC driver
问题描述
我正在尝试使用以下代码动态加载JDBC驱动程序:
I'm trying to load the JDBC driver dynamically with this kind of code:
try{
URL[] url={new URL("file:libs/mysql-connector-java-5.1.21.jar")};
URLClassLoader loader = new URLClassLoader(url, System.class.getClassLoader());
loader.loadClass(drivername);
Enumeration<Driver> drivers = DriverManager.getDrivers();
while(drivers.hasMoreElements()){
Driver driver = drivers.nextElement();
System.out.println("driver:"+driver);
}
Class.forName(drivername, true, loader);
drivers = DriverManager.getDrivers();
while(drivers.hasMoreElements()){
Driver driver = drivers.nextElement();
System.out.println("driver:"+driver);
}
Connection connect = DriverManager.getConnection(jdbcurl, user,
password);
return connect;
}
catch (MalformedURLException e){
e.printStackTrace();
return null;
}
第一个while循环显示类路径的驱动程序:
The first while-loop shows the drivers of the classpath:
driver:sun.jdbc.odbc.JdbcOdbcDriver@35712651
driver:oracle.jdbc.OracleDriver@58df0438
driver:com.ibm.db2.jcc.DB2Driver@525c7734
driver:SQLServerDriver:1
和第二个循环显示相同的驱动程序,但没有MySQL驱动程序.
and the second loop shows the same drivers, but without the MySQL driver.
我的问题是为什么?我错过了什么吗?
My Question is why? Did I miss something?
我在DriverManager
的JavaDoc中阅读了如果驱动程序已加载,驱动程序会尝试通过drivermanager注册自己.在我的代码中,该名称应为loader.loadClass(drivername);
.我认为这段代码应该调用静态部分,例如:
I read in the JavaDoc of DriverManager
that every driver tries to register himself by the drivermanager, if the driver is loaded. In my Code this should be loader.loadClass(drivername);
. I thought this code should invoke the static part for example:
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
of Driver
类.
推荐答案
DriverManager和类加载器的已知问题,请参见:
that's a known issue with DriverManager and classloaders, see:
http://www.kfu.com/~nsayer/Java/dyn-jdbc.html
驱动程序定义(基本上是委托):
Driver definition (basically a delegate):
class DriverShim implements Driver {
private Driver driver;
DriverShim(Driver d) { this.driver = d; }
public boolean acceptsURL(String u) throws SQLException {
return this.driver.acceptsURL(u);
}
public Connection connect(String u, Properties p) throws SQLException {
return this.driver.connect(u, p);
}
// and so on....
使用示例:
URL u = new URL("jar:file:/path/to/pgjdbc2.jar!/");
String classname = "org.postgresql.Driver";
URLClassLoader ucl = new URLClassLoader(new URL[] { u });
Driver d = (Driver)Class.forName(classname, true, ucl).newInstance();
DriverManager.registerDriver(new DriverShim(d));
DriverManager.getConnection("jdbc:postgresql://host/db", "user", "pw");
这篇关于动态加载JDBC驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!