Java 类路径找不到 MySQL 驱动程序

Java classpath cannot find MySQL driver

每当我运行以下代码时:

import com.mysql.jdbc.Driver;

public void insertIntoMysql() {

    // Print out classloader information
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL[] urls = ((URLClassLoader) cl).getURLs();
    String urlStr = "";
    for (int i=0; i < urls.length; i++) {
       urlStr += urls[i].getFile() + "\n";
    }
    System.out.println("Classpath:\n" + urlStr);

    // connect to mysql
    Class.forName("com.mysql.jdbc.Driver");
    String myUrl = "jdbc:mysql://localhost:3306/Compass";
    Connection conn = DriverManager.getConnection(myUrl, "root", "newpoint");

    ...
}

我在 Class.forName 行收到 "ClassNotFoundException: com.mysql.jdbc.Driver" 错误。但是,我的类路径打印为:

Classpath: 
... 
/C:/myProjectDir/

我的类路径中有以下 jar“/C:/myProjectDir/mysql-connector-java-5.0.8-bin.jar”。

我已经重新启动了程序,以防类加载器在程序启动时加载所有内容,但我一直收到该错误。

有什么想法吗?

目前看来您的 class 路径上只有您的项目目录,而不是 mysql-connector-java-5.0.8-bin.jar文件本身。

在Java中,class路径中包含的内容规则如下:

  • For class files in an unnamed package, you include the directory that contains the class files
  • For class files in a named package, you include the directory that contains the root package, which is the first package in the full package name
  • For a JAR or zip file that contains class files, you include the name of the zip or JAR file

要获取 mysql 驱动程序,您需要按名称将驱动程序 jar 添加到 class 路径:

Classpath: 
... 
/C:/myProjectDir/
/C:/myProjectDir/mysql-connector-java-5.0.8-bin.jar
... 

有关详细信息,请查看 Java tutorial on PATH and CLASSPATH, and the Oracle documentation on Setting the Class Path