Java Reference
In-Depth Information
forming manual closes. The following code demonstrates how to use
try-with-re-
sources
to open a connection, create a statement, and then close both the connection
and statement when finished.
try (Connection conn = createConn.getConnection();
Statement stmt = conn.createStatement();) {
ResultSet rs = stmt.executeQuery(qry);
while (rs.next()) {
// PERFORM SOME WORK
}
} catch (SQLException e) {
e.printStackTrace();
}
As seen in the previous pseudo-code, nested
try-catch
blocks are often required
in order to clean unused resources. Proper exception handling sometimes makes JDBC
code rather laborious to write, but it will also ensure that an application requiring data-
base access will not fail, causing data to be lost.
13-3. Querying a Database and Retriev-
ing Results
Problem
A process in your application needs to query a database table for data.
Solution
Obtain a JDBC connection using one of the techniques as described in Recipe 13-1,
and then use the
java.sql.Connection
object to create a
Statement
object. A
java.sql.Statement
object contains the
executeQuery()
method, which
parses a string of text and uses it to query a database. Once you've executed the query,
you can retrieve the results of the query into a
ResultSet
object. The following ex-
ample queries a database table named
RECIPES
and prints the results: