Beanshell won't load my dynamically added JDBC Driver class?
-
31-12-2020 - |
Question
Using JDK1.6.0_16, I have this simple program where I am trying to get beanshell 2.0b4 to load a .jar dynamically (as the documentation suggests it will do) and I am having no luck. The documentation says that if I use beanshells' getClass() method then it will load jars that were previously loaded by the "addClassPath()" method. It is not working. I need help on this...
//debug();
addClassPath("mysql-connector-java-5.1.15.jar");
import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Arrays;
System.out.println("MySQL Connect Example.");
System.out.println("Classpath: " + Arrays.toString( getClassPath() ) + "\n");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try {
Class driverClass = getClass( driver );
if(driverClass != null) {
Driver driver = driverClass.newInstance();
if(driver != null) {
DriverManager.registerDriver(driver);
}
}
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
This problem I am having strongly suggests that the getClass() method (of beanshell) is unable to see its own dynamically changed classpath.
NOTE: this code works only when I put the mysql.jar file into the jre/lib/ext directory (which is where the legacy jre classloader can load it; not the beanshell classloader)
Solution
this is probably not a beanshell thing, jdbc has issues loading drivers across classloaders (check out the class javadoc for ClassLoader, and see hacks like this).