How does DriverManager identify the type of driver loaded into JVM
October 9, 2012 Leave a comment
Typical JDBC code to connect to the database is:
/**
* Responsible for loading the Driver.java class into
* into JVM at runtime
*/
Class.forName("org.gjt.mm.mysql.Driver");
/**
* DriverManager getting the connection object
* based on the driver loaded above
*/
Connection con=DriverManager.getConnection(url);</code></div>
QUESTION is who will instantiate the class that is loaded and who will register that class with DM? It is done through the static block of code in the Driver.java class which will instantiate itself and register with DriverManager
Here is the Driver.java source from MySQL
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
//
// Register ourselves with the DriverManager
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
/**
* Construct a new driver and register it with DriverManager
*
* @throws SQLException
* if a database error occurs.
*/
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
}
}</code></div>
<div>
Recent Comments