Where to close java PreparedStatements and ResultSets?

后端 未结 13 2206
忘了有多久
忘了有多久 2020-11-29 02:26

Consider the code:

PreparedStatement ps = null;
ResultSet rs = null;
try {
  ps = conn.createStatement(myQueryString);
  rs = ps.executeQuery();
  // process         


        
13条回答
  •  抹茶落季
    2020-11-29 02:59

    Also note:

    "When a Statement object is closed, its current ResultSet object, if one exists, is also closed. "

    http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Statement.html#close()

    It should be sufficient to close only the PreparedStatement in a finally, and only if it is not already closed. If you want to be really particular though, close the ResultSet FIRST, not after closing the PreparedStatement (closing it after, like some of the examples here, should actually guarantee an exception, since it is already closed).

提交回复
热议问题