While connecting to MySQL database I do following steps
Connection con = null;
Resultset rs = null;
Statement st = null;
Class.forName(\"com.mysql.jdbc.Drive
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.DriverApplications no longer need to explictly load JDBC drivers using Class.forName().