简体   繁体   中英

Why do I get java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver when mysql-connector-java-8.0.16.jar is in the classpath?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM