nikos nikos - 18 days ago 5
Java Question

ClassNotFoundException: com.mysql.jdbc.Driver

This question has been asked a lot here, but i still can't fix my problem:
I put

mysql-connector-java-5.1.18-bin
into
C:\Program Files\Java\jre6\lib\ext
folder.
I have this code:

// Load the database driver
Class.forName("com.mysql.jdbc.Driver");
// Get a connection to the database
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysql", "root", "4958ps");
// Get a statement from the connection
Statement stmt = conn.createStatement() ;
// Execute the query
ResultSet rs = stmt.executeQuery( "SELECT * FROM Cust" ) ;
// Loop through the result set
while( rs.next() )
System.out.println( rs.getString(1) ) ;
// Close the result set, statement and the connection
rs.close() ;
stmt.close() ;
conn.close() ;
} catch( SQLException se ) {
System.out.println( "SQL Exception:" ) ;
// Loop through the SQL Exceptions
while( se != null ) {
System.out.println( "State : " + se.getSQLState() ) ;
System.out.println( "Message: " + se.getMessage() ) ;
System.out.println( "Error : " + se.getErrorCode() ) ;
se = se.getNextException() ;
}
} catch( Exception e ) {
e.printStackTrace();
}


and i get a ClassNotFoundException with the following stack trace:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at pack.Test.main(Test.java:14)


I also changed
CLASSPATH
variable to be
C:\Program Files\Java\jre6\lib\ext\mysql-connector-java-5.1.18-bin

Any ideas?

Answer

The zip you downloaded should contain a file named mysql-connector-java-5.0.8-bin.jar or similar. Version might be different. Check that it is present and check that it is directly in your classpath (not in a subdirectory etc.).

If that's alright, check that your classpath variable is not overwritten by something else. If you execute your program manually do it like this: java -cp "C:\Program Files\Java\jre6\lib\ext\mysql-connector-java-5.0.8-bin.jar:." YourClass

If you are using an IDE such as eclipse, check your build-path settings there. (In eclipse you would right click your project -> Properties -> Java Build Path -> Add external JARs and then supply the path of your connector...jar.