I have come across this pattern. Is it OK to reuse a Connection
object within a single method when you need multiple SQL statements to execute?
My initial thought is to close all of the resources before moving on:
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = ConnectionFactory.getConnection();
ps = conn.prepareStatement("SELECT * FROM MYTABLE WHERE COL=?");
ps.setString(1, "val");
rs = ps.executeQuery();
// get values used to determine the next statement type
} catch (SQLException e) {
LOG.error("SQL failed.", e);
} finally {
if(rs != null){rs.close();}
if(ps != null){ps.close();}
if(conn != null){conn.close();}
}
// Then another SQL statement is needed (either an UPDATE or INSERT).
// Repeat the same pattern to open, use and close the connection
Is it just as safe to do the following? And if it is safe, is there a real benefit?
//... boilerplate
try {
conn = ConnectionFactory.getConnection();
ps = conn.prepareStatement("SELECT * FROM MYTABLE WHERE COL=?");
ps.setString(1, "val");
rs = ps.executeQuery();
// ... more
ps = conn.prepareStatement("UPDATE MYTABLE SET COL=?")
// ... etc
} finally {
if(rs != null){rs.close();}
if(ps != null){ps.close();}
if(conn != null){conn.close();}
}