2

In JDBC we use the

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();

method to load the object in memory. Then when we use the DriverManager class to get a connection to the Sql Server, the DriverManager automatically uses the appropriate drivers from the set of drivers loaded in memory. Can the DriverManager concept be compared with the Provider design pattern used in .net ? If not, then what exactly do we mean by

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")

method and why don't we create the object of the sql server driver class using the new keyword ?

Ravinder Singh
  • 846
  • 1
  • 7
  • 17
  • Also note that for JDBC 4.0 drivers this is not needed anymore: http://download.oracle.com/javase/6/docs/api/java/sql/DriverManager.html – Puce Feb 21 '11 at 17:11

2 Answers2

1

Class.forName("XXXDriver") invokes static block of XXXDriver. Usually the static block invokes DriverManager.registerDriver(new XXXDriver()) to register itself to DriverManager.

Something like:

public class XXXDriver implements Driver{
  static{
    //Be invoked by Class.forName("XXXDriver")
    DriverManager.registerDriver(new XXXDriver())
  }
...
}
卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130
0

Unfortunately I don't know about the provider pattern in .Net. But here is what that Class.forName() magic is for.

You don't instantiate the class via newInstance(). forName() is enough. (Ok, I see the reason for instance creation in BalusC's answer.)

The JDBC specification mandates that every JDBC driver registers itself with DriverManager.registerDriver(). This is done via a static block that gets executed when the class is loaded. Class loading is initiated via Class.forName().

musiKk
  • 14,751
  • 4
  • 55
  • 82