Where to close java PreparedStatements and ResultSets?

后端 未结 13 2264
忘了有多久
忘了有多久 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 03:01

    Building on @erickson's answer, why not just do it in one try block like this?

    private void doEverythingInOneSillyMethod(String key) throws MyAppException
    {
      try (Connection db = ds.getConnection();
           PreparedStatement ps = db.prepareStatement(...)) {
    
        db.setReadOnly(true);
        ps.setString(1, key);
        ResultSet rs = ps.executeQuery()
        ...
      } catch (SQLException ex) {
        throw new MyAppException("Query failed.", ex);
      }
    }
    

    Note that you don't need to create the ResultSet object inside the try block as ResultSet's are automatically closed when the PreparedStatement object is closed.

    A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

    Reference: https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html

提交回复
热议问题