Search code examples
javamysqljdbcbeanshell

JDBC Driver isn't loading properly in Java


Whenever I run the following code:

public void insertIntoMysql() {

    URLClassLoader childCl = new URLClassLoader(new URL[] {new URL("file:///myProjectDir/lib/mysql-connector-java-5.0.8-bin.jar")}, this.getClass().getClassLoader());

    try {
        // connect to mysql
        Class.forName("com.mysql.jdbc.Driver", true, childCl);
        String myUrl = "jdbc:mysql://localhost:3306/myDB";
        Connection conn = DriverManager.getConnection(myUrl, "root", "adminpw");

        ...
    } catch {
        ...
    }
}

I get a "java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/myDB" error when the DriverManager is called.

I'm guessing this has something to do with the fact that I loaded my driver with a custom classloader (I'm unable to modify the calling code, so can't change the classpath that is loaded when my script is called). It seems to find the driver just fine in the Class.forName line, but it's like that class was never loaded just two lines later.

Any thoughts?

--- UPDATE ---

I figured out how to add a jar to my classpath at runtime using a BeanShell util, removed the outdated forName, and stopped using a custom classloader. My updated code is below:

import com.mysql.jdbc.Driver;

public void insertIntoMysql() {

    try {
        addClassPath("/lib/mysql-connector-java-5.0.8-bin.jar");
        // printing out the classpath URLs here shows several
        // jar files along with the one I just added:
        // file:/C:/myProjectDir/lib/mysql-connector-java-5.0.8-bin.jar

        // connect to mysql
        String myUrl = "jdbc:mysql://localhost:3306/myDB";
        Connection conn = DriverManager.getConnection(myUrl, "root", "adminpw");

        ...
    } catch {
        ...
    }
}

However, I still get the same SQLException that I was originally getting even though my class path has been updated.

I also tried calling BeanShell's "reloadClasses()" method right after adding the new classpath, to no avail.


Solution

  • Yes this has to do with the custom classloader used to load the class. This is also mentioned in the Javadocs of DriverManager:

    When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.