4

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?

3
  • 1
    The snippet of classpath you printed has c:/myProjectDir on the classpath, not c:/myProjectDir/mysql-connector-java-5.0.8-bin.jar. Are you sure you have the jar on the classpath, and not just the directory? Commented Mar 25, 2015 at 18:22
  • I might just have the directory... I don't have the jar specifically on there. Guess I thought it would be loaded since it was within that directory, but I need to explicitly include the jar itself? Commented Mar 25, 2015 at 18:28
  • Correct. I'll expand my comment into an answer. Commented Mar 25, 2015 at 19:08

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.