JDBC Drivers and Class.forName

Have you ever wondered why you need to explicitly load a JDBC Driver class using Class.forName or calling a classloader directly?

Why doesn’t the JDBC API DriverManager seem to be able to find the class itself?

If you don’t load the JDBC Driver class manually, you’ll get an exception telling you that no suitable driver was found for the given JDBC connection string.

This seems a very weird thing, as Java is all about dynamic and transparent classloading, and needed classes are loaded into the VM whenever needed.

Answer
When a class is loaded by a classloader, the static code blocks in the class are executed. The JDBC Driver classes register themselves to the JDBC API when loaded, and they are assigned to handle database connection for certain JDBC connection strings.

When you then ask the JDBC API for a JDBC Connection to a certain database by doing something like this:

DriverManager.getConnection ( “jdbc:mysql://dbhost/mydb” );

then the driver manager can handle your request by iterating over all registered (classloaded) driver classes, and decide which driver should be taking care of the given connection string.

Remark
Please remark that you only have to classload the Driver class of the JDBC driver, all other classes needed for the JDBC connection are loaded when needed.

After all, only the driver registers itself with the JDBC Driver Manager.