Whenever I run the following code:
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");
...
}
I get a "ClassNotFoundException: com.mysql.jdbc.Driver" error on the Class.forName line. However, my classpath prints out as:
Classpath:
...
/C:/myProjectDir/
and I have the following jar "/C:/myProjectDir/mysql-connector-java-5.0.8-bin.jar" within my classpath.
I've restarted the program just in case the ClassLoader is loading everything when the program starts, but I keep getting that error.
Any thoughts?
解决方案
Currently it looks like you only have your project directory on your class path, and not the mysql-connector-java-5.0.8-bin.jar file itself.
In Java, the rules for what to include on the classpath are as follows:
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
To pick up the mysql driver, you'll need to add the driver jar to the class path by name:
Classpath:
...
/C:/myProjectDir/
/C:/myProjectDir/mysql-connector-java-5.0.8-bin.jar
...
For more information, take a look at the Java tutorial on PATH and CLASSPATH, and the Oracle documentation on Setting the Class Path.