Friday, September 13, 2013

How JDBC driver will be register ?


 JDBC Driver Registration: 

We have two main chances to Load or Register JDBC driver.

1) Using Class.forName("..");
2) Using DriverManager.registerDriver(...);

Already we know that, The first step in JDBC program is driver loading.

But when we write driver loading code, How the driver object is available in the next step of getting the connection object.


example : 

JDBC program code:

         Class.forName("com.mysql.jdbc.Driver");//here no return type
         Connection conn = DriverManager.getConnection(url, username, password);



But still we are able to get the connection object using DriverManager class.


Observe carefully, 

The Driver class "com.nysql.jdbc.Driver" contains one static block, and this static block will be executed while loading this class into jvm's memory by ClassLoader.

This static block has the code to register(assign) MySQL's Driver class object to one of the static varible in DriverManager class.

example code :
 
                static {
                 try {
                java.sql.DriverManager.registerDriver(new Driver());
           } catch (SQLException E) {
              throw new RuntimeException("Can't register driver!");
               }
                   } //end block , code from   com.mysql.jdbc.Driver   

The above code will assign it's object to one of the static varible of DrierManager class.

 
//code from    java.sql.DriverManager 
private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<DriverInfo>(); 
 
 
The above static variable is available for our JDBC application. So that, the second step "getting connection object" is able to execute and returns the Connection object. 

We can easily understand, If we compare this technique with System.out.println().

System is a class and out is static variable which points to PrintStream object and println() is overloaded method available in PrintStream class.

The out variable is assigned with the PrintStream obect while this System class loading into memory.

I think you understood my intention from the above code.

Note: The second style of Driver Loading is also same.


No comments:

Post a Comment