Reputation: 33
I get a java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver when I type this into the windows command line
javac src/*.java -d class -cp lib/*
java DBTest -cp lib/*
I have also tried using com.mysql.cj.jdbc without Driver at the end. I add newInstance() to line 11 so it was:
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
but there was no change.
I also tried it without Class.forName() since this is deprecated, but I got a java.sql.SQLException: No suitable driver found
mysql-connector-java-8.0.16.jar is the only file in lib. I have also tried putting it in in the folder where I run DBTest.java. I set the Classpath from the command line using
set CLASSPATH = .
and by creating the environment variable CLASSPATH through advanced system settings. I then tried compiling and running with and without -cp since it should be checking the current directory for the jar file.
I also tried to run this in eclipse, but eclipse crashed and will no longer open.
import java.sql.*;
public class DBTest{
public static void main(String args[]) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from employees Limit 10");
while(rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getDouble(3));
}
con.close();
}catch(Exception e) {
System.out.println(e);
}
}
}
The entire error message is java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
Upvotes: 0
Views: 2021
Reputation: 108962
You have the arguments to java
in the wrong order. Putting arguments after the classname will pass those arguments to the main method of your class, it won't set the classpath.
You need to put the arguments before the classname. Also -d class
is not a valid argument for java
. In short, you need to use:
java -cp class:lib/* DBTest
Upvotes: 1