我正在尝试使用这种代码动态加载 JDBC 驱动程序:
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 循环显示了类路径的驱动程序:
driver:sun.jdbc.odbc.JdbcOdbcDriver@35712651
driver:oracle.jdbc.OracleDriver@58df0438
driver:com.ibm.db2.jcc.DB2Driver@525c7734
driver:SQLServerDriver:1
第二个循环显示相同的驱动程序,但没有 MySQL 驱动程序。
我的问题是为什么?我错过了什么?
我在 JavaDoc 中DriverManager
读到,如果驱动程序已加载,每个驱动程序都会尝试通过 drivermanager 注册自己。在我的代码中,这应该是loader.loadClass(drivername);
. 我认为这段代码应该调用静态部分,例如:
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}