It seems that every time I want to perform a db query, I have to write the following:
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
conn = dataSource.getConnection();
stmt = conn.prepareStatement(sql);
// ...set stmt params
rset = stmt.executeQuery();
while(rset.next()) {
// Do something interesting
}
} finally {
try { if (rset != null) rset.close(); } catch(SQLException e) { }
try { if (stmt != null) stmt.close(); } catch(SQLException e) { }
try { if (conn != null) conn.close(); } catch(SQLException e) { }
}
Is this really the best way to do this? Is there a way to at least reduce some of the clutter?
Edited: as some of the comments pointed out, this code wasn't long enough.