0

I'm trying to connect to a database on localhost. Mysql is running and the database name is employees. I confirmed that the port, username, and password are correct.

The java, class, and jar file are in the same folder. I tried adding the jar file to my CLASSPATH in the system environment variables and I tried adding it using -cp like below.

javac -cp . relearnjdbc.java

javac -cp ./mysql-connector-java-8.0.20.jar relearnjdbc.java

javac -cp *.jar relearnjdbc.java

I also tried separating the files into their own folders src, class, and bin.

javac -cp ../bin -d ../class relearnjdbc.java

This is my code

public class relearnjdbc {
    public static String url = "jdbc:mysql://localhost:3306/employees";
    public static String username = "root";
    public static String password = "root";

    public static void main(String[] args){
        System.out.println("Connecting to DB...");

    
        try{
            //Class.forName("com.mysql.jdbc.Driver");
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            //Connection connection = DriverManager.getConnection(url, username, password);
            DriverManager.getConnection(url, username, password);
            System.out.println("Connected!");
        }catch (Exception e){
            throw new IllegalStateException("cannot connect to DB ", e);
        }
    }
}

These give java.lang.ClassNotFoundException. I know its deprecated, but it was in a lot of answers to similar questions.

Class.forName("com.mysql.jdbc.Driver").newInstance();
Class.forName("com.mysql.jdbc.Driver");

I'm not using an IDE, tomcat, netbeans, apache, phpadmin, or anything else. As far as I can tell a lot of other people that have asked this question were using one of these or they didn't have the jar file in their classpath.

D.B
  • 33
  • 7
  • 1
    You only show that you specify the classpath when **compiling**, but how do you **run** your Java application? My guess is that you didn't specify the classpath when **running** your Java application. – Mark Rotteveel Jul 08 '20 at 08:17
  • @MarkRotteveel I tried specifying when compiling only. I tried adding it to my environmental variables and specifying when running, and all three. Adding it to the environmental variable and using -cp when compiling and running. – D.B Jul 08 '20 at 20:17

1 Answers1

1

The name of the class that implements java.sql.Driver in MySQL Connector/J has changed from com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver. The old class name has been deprecated docs

try Class.forName("com.mysql.cj.jdbc.Driver").newInstance();

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
  • it still throws the ClassNotFoundException – D.B Jul 08 '20 at 00:57
  • The name changed, but the old class name (`com.mysql.jdbc.Driver`) is still available for backwards compatibility and works just fine. If the OP gets a `ClassNotFoundException`, then the driver is not on the classpath. – Mark Rotteveel Jul 08 '20 at 08:15