【问题标题】:Close java PreparedStatement and ResultSets关闭 java PreparedStatement 和 ResultSets
【发布时间】:2016-04-25 17:34:58
【问题描述】:

下面的代码无法编译,因为 PreparedStatement.close() 和 ResultSet.close() 都会抛出 java.sql.SQLException。那么我应该在 finally 子句中添加一个 try/catch 块吗?或者将 close 语句移到 try 子句中?或者只是不打扰打电话关闭?

PreparedStatement ps = null;
ResultSet rs = null;
try {
  ps = conn.createStatement(myQueryString);
  rs = ps.executeQuery();
  // process the results...
} catch (java.sql.SQLException e) {
  log.error("an error!", e);
  throw new MyAppException("I'm sorry. Your query did not work.");
} finally {
  ps.close();
  rs.close();
}

【问题讨论】:

    标签: java mysql jdbc


    【解决方案1】:

    利用 Java 7 中引入的新功能try-with-resources Statement

    例如...

    try (PreparedStatement ps = conn.createStatement(myQueryString)) {
        // bind parameters
        try (ResultSet rs = rs = ps.executeQuery()) {}
            // process the results...
        }
    } catch (java.sql.SQLException e) {
        log.error("an error!", e);
        throw new MyAppException("I'm sorry. Your query did not work.");
    }
    

    【讨论】:

      【解决方案2】:

      使用 try-with-resources 块(在 Java 7 中引入),它会自动为您关闭资源。

      这是您发布的等效代码,用 try-with-resource 块重写:

      try(PreparedStatement ps = conn.createStatement(myQueryString)) 
      {
          ResultSet rs = ps.executeQuery();
          // process the results...
      } catch(SQLException e) {
          log.error("an error!", e);
          throw new MyAppException("I'm sorry. Your query did not work.");
      }
      

      注意:
      这里不需要在ResultSet上调用close(),因为根据Statement.close()文档:

      当一个 Statement 对象被关闭时,它当前的 ResultSet 对象(如果存在的话)也被关闭。

      【讨论】:

        【解决方案3】:

        有几种方法可以做到这一点。

        首先也是最简单的,如果您使用的是 Java 7,请按照其他答案中的说明实现 try-with-resource

        第二种方法,您可以在 finally 块中添加一个 try/catch。建议先关闭ResultSet,再关闭Statement,最后关闭Connection

        finally {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
        }   
        

        第三种方法是使用外部库,例如Commons DbUtils,它会为您处理所有关闭。

        finally {
            org.apache.commons.dbutils.DbUtils.closeQuietly(rs);
            org.apache.commons.dbutils.DbUtils.closeQuietly(ps);
        }
        

        【讨论】:

          猜你喜欢
          • 2010-09-24
          • 2012-08-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-10
          相关资源
          最近更新 更多