Java Reference
In-Depth Information
C ONNECTING TO THE D ATABASE
The typical JDBC sequence required to access the database is slightly involved but
quite straightforward after some practice. You create a connection to the database;
you perform some actions, such as querying or updating; then you free the re-
sources and the connections.
The first step is to create a connection to the database. To do this you need to
have the JDBC driver class in your CLASSPATH. Most often the driver will be in a
jar file supplied by the JDBC developer or vendor. To establish the connection, first
you must load the driver. Then you can use the DriverManager class to establish the
actual connection.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection dbConnection =
DriverManager.getConnection("jdbc:odbc:mydata");
Although I have not discussed the class named Class , don't be confused by the
Class.forName() that is used to accomplish the driver load. Every VM has a class
loader that performs the task of locating the actual code on disk, performing re-
quired integrity and security checks on it, and loading it into memory. As a com-
plex program executes using many different classes, the driver-loading process
takes place transparently behind the scenes. The forName() method is one way of
loading a class explicitly in code (similar to an import statement that is resolved at
runtime). If the class loader is unable to find the class, it will throw a ClassNot-
FoundException ; otherwise, the class loader locates the class in the CLASSPATH and
performs the same tasks it would for any other class. In the preceding code, you are
loading the Sun JDBC-ODBC Bridge Driver explicitly by passing the correct class
name to the forName() method.
After the driver is loaded, you can obtain a connection to a specific database that
the driver supports by using the DriverManager . When the driver is loaded, it inter-
acts with the DriverManager class to register itself. This registration process allows the
DriverManager to map the URL string that is passed from the getConnection()
method to a driver. The driver interprets the URL string and establishes the con-
nection to the actual database.
The required conventions for the URL string are different for each driver, so
you must consult the driver documentation for the exact parameters needed to es-
tablish the connection. In the example ( "jdbc:odbc:mydata" ), you are using JDBC
to connect to an ODBC data source called “mydata.” The JDBC-ODBC Bridge
Driver requires the information in this format to establish the connection. If you
are unfamiliar with ODBC and data sources, don't worry. I will cover the topic
more thoroughly later in this chapter.
Search WWH ::




Custom Search