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;
}
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
and the second loop shows the same drivers, but without the MySQL driver.
My Question is why? Did I miss something?
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 the Driver
class.