Posts

Showing posts from August, 2012

How class.forName loads the Database Driver in JDBC

When Class.forName() is called with an argument like this: Class.forName("org.gjt.mm.mysql.Driver"); the classloader attempts to load and link the Driver class in the “org.gjt.mm.mysql” package and if successful, the static initializer is run. The MySQL Driver static initializer looks like this: static {   try {     java.sql.DriverManager.registerDriver(new Driver());   } catch (SQLException E) {     throw new RuntimeException("Can't register driver!");   } } So it calls a static method in the java.sql.DriverManager class which apparently registers a copy of itself when it loads.   To understand the why you have to look at the next line in the initial code example: Connection con = DriverManager.getConnection(url,   "myLogin", "myPassword"); The DriverManager class returns a database connection given a JDBC URL string, a username and a password. In order to create that connection, the DriverManager class has to know