JDBC driver error and cannot connect to MySQL

Viewed 56

I keep getting the error messages when I run my code attempting to connect to a MySQL server

Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:375)

This is my code. I've made sure to add connector/J to the classpath and still no change.

import java.sql.*;

public class App {
    
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/vehicle", "root", "root"); // For MySQL only

        vehicle focus = new vehicle("Ford", "Focus", 200, 2004, 3000);

        System.out.println(focus.getMake());
    }
}
1 Answers

First of all, loading the JDBC driver using Class.forName is not necessary since JDBC 4.0 which was made available in 2006 (the driver registers its implementation as service provider and will be loaded by the ServiceLoader).

Just remove this line and it should work. If you need the class name, its a good idea to consult the documentation of Connector/J. Take care to read the docs for the correct driver version because the class name changed (currently it's com.mysql.cj.jdbc.Driver).

Update

As Mark Rotteveel pointed out, Class.forName("com.mysql.jdbc.Driver") will not lead to a ClassNotFoundException when used with newer version of Connector/J. At least the newest driver produces a warning:

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

Knowing this, removing Class.forName won't help since the exception simply means, that the driver is not on the class path.

Related