动态加载 JDBC 驱动程序
2022-09-03 12:44:15
我正在尝试使用此类代码动态加载 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驱动程序。
我的问题是为什么?我错过了什么吗?
我在DriverManager
的JavaDoc中读到,如果驱动程序已加载,则每个驱动程序都会尝试由驱动程序管理器注册自己。在我的代码中,这应该是.我认为这段代码应该调用静态部分,例如:loader.loadClass(drivername);
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}