I have JDBC connection code similiar to the following from the Java JDBC tutorial:
public static void viewTable(Connection con) throws SQLException {
Statement stmt = null;
String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
stmt.close();
}
}
My problem with this way of handling to connection is that it closes the statement in the finally block and the method throws any SQLException that may occur. I don’t want to do that, because I want any problems handled within this class. However, I do want that Statement#close() call in the finally block so that it is always closed.
Right now I’m placing this code in a separate method that returns a HashMap of the fields returned to that the exception is handled in-class. Is there another, possibly better way to handle this?
EDIT: The close() SQLException is the one I am concerned with. If possible I’d like to handle that within the method. I could write a try/catch in the finally, but that seems really awkward.
You have several problems:
You need to close the ResultSet explicitly. Some drivers are less forgiving about forgetting to close the ResultSet than others, it doesn’t hurt anything to be sure to close it.
You ought to catch the SQLException thrown by the Statement.close, because it’s not interesting and only serves to mask the interesting exception (if you have something in this method throw an exception, then the finally throws an exception on the way out, you get the exception from the finally block and lose the first exception). There really isn’t anything that you can do if a close method call throws an exception, just log it and go on, it is not something to be concerned about.
You should give up on the idea of handling all sqlexceptions in this method, the SQLException thrown by statement.executeQuery is the one that is worthwhile and it ought to be propagated if something goes wrong. It’s likely other code in your application will want to know if your sql here succeeded or not and that’s what throwing exceptions is for.
Personally I’d suggest using a library like Ibatis or spring-jdbc for this. JDBC is error-prone and tedious and it’s better to take advantage of existing tools.