JDBC 驱动程序未在 Java 中正确加载

JDBC Driver isn't loading properly in Java

每当我运行以下代码时:

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 {
        ...
    }
}

调用 DriverManager 时出现 "java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/myDB" 错误。

我猜这与我使用自定义 classloader 加载我的驱动程序有关(我无法修改调用代码,因此无法更改 class调用我的脚本时加载的路径)。似乎在 Class.forName 行中找到驱动程序就好了,但就好像 class 从未在两行之后加载。

有什么想法吗?

---更新---

我想出了如何在 运行 时间使用 BeanShell 实用程序将 jar 添加到我的 class 路径,删除过时的 forName,并停止使用自定义 class 加载程序。我的更新代码如下:

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 {
        ...
    }
}

但是,即使我的 class 路径已更新,我仍然得到与最初相同的 SQLException。

我还尝试在添加新的 class 路径后立即调用 BeanShell 的 "reloadClasses()" 方法,但无济于事。

是的,这与用于加载 class 的自定义 classloader 有关。 DriverManager:

的Javadocs中也提到了这一点

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.

jar 文件应该在您的 类路径