In modern Java (specifically JDBC 4.0 and later), you generally do not need to write code to load the driver.
The DriverManager uses the Service Provider Interface (SPI) to automatically discover and load any JDBC drivers present on your classpath.
1. The Modern Way: Automatic Discovery
As long as the driver JAR is on your classpath (e.g., added via Maven or Gradle), you can simply request a connection:
package org.kodejava.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseApp {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/my_database";
String user = "username";
String password = "password";
// No Class.forName() needed!
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connected successfully!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2. The Legacy Way (Avoid if possible)
In older versions of Java (pre-Java 6) or specific legacy environments, you might see this line:
Class.forName("com.mysql.cj.jdbc.Driver");
While this still works, it is considered boilerplate in modern applications because the DriverManager handles this initialization automatically during the first call to getConnection().
3. How to ensure it works
The “loading” now happens at the project configuration level rather than the code level:
- Maven: Add the dependency to your
pom.xml. - Gradle: Add the implementation to your
build.gradle. - Plain JARs: Ensure the driver
.jarfile is included in your IDE’s libraries or the-classpathargument when running the app.
Why did this change?
The JDBC 4.0 specification introduced the META-INF/services/java.sql.Driver file inside driver JARs. When you call DriverManager.getConnection(), Java scans the classpath for these files and registers any drivers it finds automatically.
