10.2 Connecting to the database 

Previous Index Next 


 To connect to a particular database requires two steps:
  1. The JDBC driver for the database must be loaded.
  2. A connection must be established with the database

Loading a JDBC driver

Before a JDBC driver can be used it must be loaded into memory. The following code loads the JDBC to ODBC bridge driver:
try
 {
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  //loads the driver
 }
catch(ClassNotFoundException e)
 {
  System.out.println("Could not load JDBC driver !");
  System.exit(1);
 }

Establishing a connection

Once the JDBC driver is loaded a Connection object needs to be created. The Connection object represents a database connection and it is used to create and execute SQL statements. The following code opens a connection to a ODBC datasource called "fred".
Connection dbConnection = null;
String url = "jdbc:odbc:fred";
String userID = "AUserID";
String password = "APassword";

try
 {
  dbConnection = DriverManager.getConnection(url, userID, password);
 }
catch (SQLException e)
 {
  System.out.println("Database Error. Could not connect : " + e);
  System.exit(1);
 }
catch (Exception e)
 {
  System.out.println("Error. Could not Connect : " + e);
  System.exit(1);
 }
The URL string that is passed to the getConnection() method is used by the DriverManager class to determine which JDBC driver to use. The URL string above specifies the use of the JDBC to ODBC bridge, using the ODBC datasource "fred".

Two types of exceptions are caught above. Most of the functions in the JDBC throw a SQLException if they have a problem, however some JDBC drivers throw other exceptions if there is a problem with in the getConnection() method.