Tuesday 20 October 2015

Need of Class.forName() to load a driver

Need of Class.forName() to load a driver

Class.forName("org.gjt.mm.mysql.Driver");
Connection con = DriverManager.getConnection(url,
"myLogin", "myPassword");

All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static an initializer only.

The MySQL JDBC Driver has a static initializer looks like this:


static {
    
try {
        java.sql.DriverManager.registerDriver(new Driver());
    } catch (SQLException E) {
        throw new RuntimeException("Can't register driver!");
    }
}


JVM executes the static block and the Driver registers itself with the DriverManager.

We need a database connection to manipulate the database and create the connection to the database, the DriverManager class has to know which database driver you want to use (static initialized).

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...