Java Reference
In-Depth Information
L
ISTING
7.3
Continued
}
catch (Exception e) {
System.err.println(e.getMessage());
}
finally {
try {
7
if ( con != null ) {
// Close the connection no matter what
con.close();
}
}
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
}
}
}
public static void main(String[] args) {
SelectDataApp selectDataApp = new SelectDataApp();
selectDataApp.selectData();
}
}
To execute a query, use the same
Statement
object as in previous examples. You just call a dif-
ferent method. The method to perform a query is
executeQuery()
. Its signature is listed here:
public ResultSet executeQuery(String sql) throws SQLException
It takes a SQL string like the
executeUpdate()
method. The difference from
executeUpdate()
is that
executeQuery()
returns a
ResultSet
object containing the results of
the query. In the example, you pass it the string
“SELECT * FROM Titles”
, which returns a
collection of rows resulting from the query.
After you have your
ResultSet
object returned from
executeQuery()
, you can iterate over it.
The following code snippet shows how the example processes the query results: