views:

476

answers:

6

I've seen this line in a sample application for using a commercial JDBC driver:

Class.forName("name.of.a.jcdb.driver")

The return value is not used.

What purpose does this line serve?

+11  A: 

It performs a static loading of that class. So anything in the static { } block, will run.

Noon Silk
Which lets the driver class register itself with the JDBC framework. This is needed to allow JDBC to properly recognize the connection URL you pass in in the later calls.
Michal
a "static" loading? is it not just loading the class, which starts any static initializer (static block AND static variables/constants)?
Carlos Heuberger
+5  A: 

In your specific example, the JDBC driver class contains a static intializer that registers the driver will the DriverManager.

Michael Borgwardt
+2  A: 

In the case of JDBC drivers the static initializer of the requested class will register the driver with JDBC’s DriverManager so that getting a connection for a driver-specific URL works.

Bombe
+2  A: 

This is used in particular for JDBC drivers. The JDBC driver class has a static initializer block that registers the class with the JDBC DriverManager, so that DriverManager knows about the driver when you later open a database connection.

In a newer version of JDBC (JDBC 3.0, I think) this is not necessary anymore, a different mechanism is used by DriverManager to find JDBC drivers.

edit - This page explains in detail how loading a JDBC driver works and how the driver registers itself with the DriverManager (the old way).

Jesper
Anybody with a link to a description of the new mechanism? I need something similar.
Thorbjørn Ravn Andersen
The javadoc for DriverManager from JDK 6 tells about a couple of methods for the DriverManager to find drivers: http://java.sun.com/javase/6/docs/api/java/sql/DriverManager.html
Bombe
+1  A: 

to manul load class in current classloader

+1  A: 

Maybe some code snippet will help. This is from Sun's JDBC-ODBC bridge driver,

//--------------------------------------------------------------------
// Static method to be executed when the class is loaded.
//--------------------------------------------------------------------


static
{  
 JdbcOdbcTracer tracer1 = new JdbcOdbcTracer();
 if (tracer1.isTracing ()) {
  tracer1.trace ("JdbcOdbcDriver class loaded");
 }

 JdbcOdbcDriver driver = new JdbcOdbcDriver ();

 // Attempt to register the driver

 try {
  DriverManager.registerDriver (driver);
 }
 catch (SQLException ex) {
  if (tracer1.isTracing ()) {
   tracer1.trace ("Unable to register driver");
  }  
 }
}

the DriverManager.registerDriver() call in a static block is executed whenever the driver is loaded through Class.forName().

This used to be the only way to register the driver. JDBC 4.0 introduced a new service registration mechanism so you don't need to do this anymore with newer JDBC 4.0 compliant drivers.

ZZ Coder