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?
forName. Returns the Class object associated with the class or interface with the given string name, using the given class loader. Given the fully qualified name for a class or interface (in the same format returned by getName ) this method attempts to locate, load, and link the class or interface.
forName() The most common approach to register a driver is to use Java's Class. forName() method, to dynamically load the driver's class file into memory, which automatically registers it. This method is preferable because it allows you to make the driver registration configurable and portable.
forName() is no longer required. Since Java 1.6, JDBC 4.0 API, it provides a new feature to discover java. sql. Driver automatically, it means the Class.
forName will do while loading drivers? It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
It performs a static loading of that class. So anything in the static { }
block, will run.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With