You can create a method that receives an SQL query and an object to process ResultSet. eg:
private void executeSql(String sql, ResultSetHandler handler) {
Statement stmt = null;
ResultSet rstmt = null;
try {
stmt = conn.createStatement();
rstmt = stmt.executeQuery(sql);
while (rstmt.next()) {
handler.handle(rstmt);
}
}
catch (SQLException e) {
}
finally {
try {rstmt.close();} catch (SQLException ex) {}
try {stmt.close();} catch (SQLException ex) {}
}
}
c ResultSetHandleris the interface:
public interface ResultSetHandler {
void handle(ResultSet rs) throws SQLException;
}
and you can create an object of an anonymous class that implements this interface, so it won’t clutter up too much.
source
share