Java Reference
In-Depth Information
IAN'S BASIC STEPS: USING A JDBC QUERY
To create a JDBC query:
1. Load the appropriate
Driver
class, which has the side effect of registering with the
DriverManager
.
2. Get a
Connection
object, using
DriverManager.getConnection()
:
Connection con = DriverManager.getConnection (dbURL, name, pass);
3. Get a
Statement
object, using the
Connection
object's
prepareStatement
or
cre-
ateStatement()
:
Statement stmt = con.prepareStatement("select * from MyTable");
4. Get a
ResultSet
object, using the
Statement
object's
executeQuery()
:
ResultSet rs = stmt.executeQuery();
5. Iterate over the
ResultSet
:
while (rs.next( )) {
int x = rs.getInt("CustNO");
6. Close the
Statement
.
7. Close the
ResultSet
.
8. If you are all done with it, close the
Connection
.
The first step in using JDBC is to load your database's driver. This is performed using some
Java JVM magic. The class
java.lang.Class
has a method called
forName( )
that takes a
string containing the full Java name for a class and loads the class, returning a
Class
object
describing it. This is part of the introspection or reflection API (see
Chapter 23
), but can be
used any time to ensure that a class has been correctly configured into your CLASSPATH.
This is the use that we'll see here. And, in fact, part of the challenge of installing JDBC