每当我运行以下代码时:
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”。
我已经重新启动了程序,以防类加载器在程序启动时加载所有内容,但我一直收到该错误。
有什么想法吗?
最佳答案
目前看起来您的类路径上只有您的项目目录,而不是 mysql-connector-java-5.0.8-bin.jar 文件本身。
在 Java 中,类路径中包含的内容的规则如下:
- 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 添加到类路径中:
Classpath:
...
/C:/myProjectDir/
/C:/myProjectDir/mysql-connector-java-5.0.8-bin.jar
...
有关更多信息,请查看 Java tutorial on PATH and CLASSPATH ,以及 Setting the Class Path 上的 Oracle 文档.
关于Java 类路径找不到 MySQL 驱动程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29263498/