4

Is it necessary to close ResultSet and PreparedStatement within one db.getConnection()? For the example below:

Connection conn = db.getConnection();
PreparedStatement pstmt = conn.prepareStatement(firstsql);
ResultSet r = pstmt.executeQuery();
// do something with the ResultSet
r.close();
pstmt.close();   // do I need close the r and pstmt here?
PreparedStatement pstmt = conn.prepareStatement(secondsql);
ResultSet r = pstmt.executeQuery();
// do something with the ResultSet again
r.close();
pstmt.close();
conn.close();
return null;

Are the codes of line 5 and line 6 necessary?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Cuero
  • 1,169
  • 4
  • 21
  • 42

2 Answers2

11

Strictly speaking, it is not necessary because you can have multiple prepared statements opened at the same time. What is necessary is to close every opened resource if it is not going to be utilised later.

Looking at your code, it doesn't ensure that the statement are, in fact, closed.

To ensure this, every close operation must be done inside a finally block: this way, it will executed whether the operation succeded or not.

Sample code:

PreparedStatement pstmt = null;
ResultSet r = null;
try {
    pstmt = conn.prepareStatement(firstsql);
    r = pstmt.executeQuery();
    // do something with the ResultSet
} finally {
    if (r != null) {
        try {
            r.close();
        } catch (SQLException e) {
            //log error
        }
    }
    if (pstmt != null) {
        try {
            pstmt.close();
        } catch (SQLException e) {
            //log error
        }
    }
}
//and do it again

This code can be greatly simplified if you are using Java 7 with the try-with-resources statement:

try (PreparedStatement pstmt = conn.prepareStatement(firstsql);
      ResultSet r = pstmt.executeQuery();) {
    // do something with the ResultSet
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
4

No. You can have multiple statements open at the same time. But you must close them eventually.

The code you've posted doesn't compile, and if it did it would have a resource leak, but that's a different issue from the question in your title.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Thank you. I understand what you mean by 'No' and 'resource leak' after read all of the comments. – Cuero Oct 02 '15 at 09:27