Java Reference
In-Depth Information
drivers is ensuring that they are in your CLASSPATH at deployment time. The advantage of
my slightly convoluted approach is that the drivers do not have to be on your CLASSPATH
at compile time. In some cases, this can allow customers to use your software with database
drivers that didn't even exist when your software was written; how's that for flexibility?
But wait, there's more! In addition to checking your CLASSPATH, this method also registers
the driver with another class called the DriverManager . How does it work? Each valid
JDBC driver has a bit of method-like code called a static initializer. This is used whenever
the class is loaded—just what the doctor ordered! So the static block registers the class with
the DriverManager when you call Class.forName() on the driver class.
For the curious, the static code block in a Driver called BarFileDriver looks something
like this:
/** Static code block, to initialize with the DriverManager. */
static
static {
try
try {
DriverManager . registerDriver ( new
new BarFileDriver ());
} catch
catch ( SQLException e ) {
DriverManager . println ( "Can't load driver" +
BarFileDriver . getClass (). getName ());
}
}
Example 18-3 shows a bit of code that tries to load two drivers. The first is the JDBC-to-
ODBC bridge described in the Introduction. The second is one of the commercial drivers
from Oracle.
Example 18-3. LoadDriver.java
public
public class
class LoadDriver
LoadDriver {
public
public static
static void
void main ( String [] av ) {
try
try {
// Try to load the jdbc-odbc bridge driver
// Should be present on Sun JDK implementations.
Class <?> c = Class . forName ( "sun.jdbc.odbc.JdbcOdbcDriver" );
System . out . println ( "Loaded " + c . getName ());
// Try to load an Oracle driver.
Class <?> d = Class . forName ( "oracle.jdbc.driver.OracleDriver" );
System . out . println ( "Loaded " + d . getName ());
} catch
catch ( ClassNotFoundException ex ) {
System . err . println ( ex );
}
Search WWH ::




Custom Search