Java Reference
In-Depth Information
Only a single driver is needed to access an ODBC data source, even if
multiple databases are to be accessed via ODBC.
Establishing a JDBC™ Connection
Once an appropriate driver is loaded, a connection must be established to
the database. Obtaining a connection locates a specific database and establishes
a database session , which is the communication pathway between the user pro-
gram and the database. A connection lasts from when the user program connects
to the database until the program disconnects or terminates. Obtaining a con-
nection is the database equivalent of opening a file, and it is within the context
of a connection that SQL statements are executed and results are returned.
To obtain a connection, line 20 calls getConnection() , passing a case-sensitive
parameter. The parameter is an address for the database in the form
jdbc:subprotocol:subname, where the subprotocol is odbc and the subname
is the data source name. Overloaded forms of this method provide additional
parameters, such as a user name and password, if required by the database. The
getConnection() method is a static method of the DriverManager class, which
provides the basic services for managing a set of JDBC™ drivers. When this
method is called, the DriverManager attempts to locate a suitable driver from the
set of registered JDBC drivers and then establish a connection to the database. If
a database access error occurs, an SQL exception is thrown. This may happen if
the data source name or the database to which it refers does not exist, which is
why they were established first. If successful, the method returns a Connection
object. A Connection object models a database connection, and its
createStatement() method is used to create a Statement object, as is done
in line 21. A Statement object typically is used for executing static SQL state-
ments and, once created, can be used to execute different statements until the
Statement object is closed. A static SQL statement is a statement in which the
parameters do not change as the program executes. Table 11-5 on the next page
lists the SQL statements used in this chapter. By convention, the SQL statement
keywords are listed in capital letters. Optional portions are enclosed within
square brackets ([]) and repeating patterns are indicated by ellipses (…).
Search WWH ::




Custom Search