0

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

D.B
  • 33
  • 7

1 Answers1

1

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
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • This gives `Error: Could not find or load main class DBTest`. Can you give me any hints as to why that may be? How was it able to find the class and execute up to line 11 before? – D.B Jun 24 '19 at 14:02
  • That would indicate that the class is in the current folder and you need to use `-cp .:lib/*` instead, which could mean that the same problem applies to the `javac` commandline as well (I don't regularly use `javac` from the commandline, but probably you need to use `javac -d class -cp lib/* src/*`. – Mark Rotteveel Jun 25 '19 at 06:35