I'm aware that a very similar question was asked here: Is it necessary to close PreparedStatement before preparing another Statement But even after looking at the answer, I'm still confused.
If say, I modify the OP's code to this:
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet r = null;
try{
conn = db.getConnection();
pstmt = conn.prepareStatement(firstsql);
r = pstmt.executeQuery();
// do something with the ResultSet
r.close(); // do I need this line?
pstmt.close(); // do I need this line?
PreparedStatement pstmt = conn.prepareStatement(secondsql);
ResultSet r = pstmt.executeQuery();
// do something with the ResultSet again
}
finally{
if(r!=null)
r.close();
if(pstmt!=null)
pstmt.close();
if(conn!=null)
conn.close();
Do I need those 2 lines? I'm aware that both r and pstmt are inevitably going to be closed(regardless of wether or not there'll be a runtime error), since they're in the finally block but r and pstmt are both pointers.
Pointers that throughout this code point to many different PreparedStatement and ResultSet objects. Wouldn't I need to close those objects before I point to other ones?
In my mind if this code was missing those 2 lines it would only ensure that only the last 2 objects to be pointed to by r and pstmt will be closed.