Saturday 1 December 2012

Why Use class.forName()

2 comments

The direct way to register the driver is,
DriverManager.registerDriver(new OracleDriver);//just an example

What Class.forName("Driver") does is, It will register the driver by calling the same method DriverManager.registerDriver(new OracleDriver);

See the below example,

Class SampleDriver{
SampleDriver(){}
static{
DriverManager.registerDriver(new SampleDriver());
}
}

Note: As you all know, The static block will be called when we load a class. That means when we put Class.forName("SampleDriver") the static block will be called where the DriverManager.registerDriver(new SampleDriver()) is invoked.

 

From the Sun's JDBC Guide at http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/drivermanager.html


  • by calling the method Class.forName. This explicitly loads the driver class. Since it does not depend on any external setup, this way of loading a driver is the recommended one for using the DriverManager framework.


  • If a has been written so that loading it causes an instance to be created and also calls DriverManager.registerDriver with that instance as the parameter (as it should do), then it is in the DriverManager's list of drivers and available for creating a connection.
  • It may sometimes be the case that more than one JDBC driver is capable of connecting to a given URL. For example, when connecting to a given remote database, it might be possible to use a JDBC-ODBC bridge driver, a JDBC-to-generic-network-protocol driver, or a driver supplied by the database vendor. In such cases, the order in which the drivers are tested is significant because the DriverManager will use the first driver it finds that can successfully connect to the given URL.


  • First the DriverManager tries to use each driver in the order it was registered. (The drivers listed in jdbc.drivers are always registered first.) It will skip any drivers that are untrusted code unless they have been loaded from the same source as the code that is trying to open the connection.

    It tests the drivers by calling the method Driver.connect on each one in turn, passing them the URL that the user originally passed to the method DriverManager.getConnection. The first driver that recognizes the URL makes the connection.



    2 comments:

    1. hi, please eplain me thread concepts and synchnization deeply with some examples specially synchronization.

      ReplyDelete
    2. I'll provide it soon..

      or Can see this link: http://onlinejavapapers.blogspot.in/2012/12/synchronization-in-java.html

      ReplyDelete