what exactly does this do Class.forName("com.mysql.jdbc.Driver").newInstance();

The Class class is located in the java.lang package, so it is distributed with java, and imported automatically into every class.

What the forName() method does, is just return the Class object for the paramater that was loaded by the class loader. The newInstance() method then returns a new instance of the class.

So then what happens is you call Class.forName(...) it returns com.mysql.jdbc.Driver.class. You then call newInstance() on that class which returns an instance of the class, whith no paramaters, so it's basically calling new com.mysql.jdbc.Driver();.


It initialize the class "com.mysql.jdbc.Driver" if found in the classpath, this imply that the driver is registered in the JDBC driver manager since the registration process is inside the static initializer of the driver class ...

There is another approach you can use to register a driver : is to use the static DriverManager.registerDriver() method.


Quoting from the JDBC Specification, Chapter 9, Section 2:

JDBC drivers must implement the Driver interface, and the implementation must contain a static initializer that will be called when the driver is loaded. This initializer registers a new instance of itself with the DriverManager.

And an example code is provided for AcmeJdbcDriver as follows:

public class AcmeJdbcDriver implements java.sql.Driver {
    static {
        java.sql.DriverManager.registerDriver(newAcmeJdbcDriver());
    }
}

And when you call Class.forName(String className), according to the API Documentation, the following happens:

A call to forName("X") causes the class named X to be initialized.

where initialization involves code in static block to be executed.

So basically, you initialize the Driver class, and in turn the class registers itself with the java.sql.DriverManager per the JDBC specification.

Please note, this is not needed anymore. Details can be found here.

The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry:

my.sql.Driver

Applications no longer need to explictly load JDBC drivers using Class.forName().