Thursday, October 11, 2007

Loading a JDBC Driver

Before a connection to a database can be established, the JDBC driver for that database must be loaded. Drivers automatically register themselves with the JDBC system when loaded. There are two ways to load a JDBC driver. The first is to specify the driver or colon-separated list of drivers on the command line:
> java -Djdbc.drivers=com.company1.Driver:com.company2.Driver MyApp


The second, and recommended method, is to call Class.forName() within the code:
try {
// Load the JDBC driver
String driverName = "org.gjt.mm.mysql.Driver";
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// Could not find the driver
}

No comments: