Loading a JDBC driver is the first and most important step in connecting a Java application to a database. The driver acts as a bridge between Java code and the database engine.
There are two main ways to load a JDBC driver:
Class.forName() (Traditional)
// Loading JDBC driver using Class.forName()
Class.forName("com.mysql.cj.jdbc.Driver");
// Creating a database connection after driver loading
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb",
"root",
"password"
);
When Class.forName() is executed, the JVM loads the driver class into memory. The driver then registers itself with DriverManager. After this, Java can establish a connection to the database.
ClassNotFoundException properlyClass.forName() and observe behavior