【问题标题】:best practice to close jdbc resultset [duplicate]关闭 jdbc 结果集的最佳实践
【发布时间】:2014-12-06 06:24:20
【问题描述】:

这是我现在的做法:

public static getConfs(Connection conn, String confNo){
    ResultSet rs = null;
    try{
        rs = conn.createStatement().executeQuery("select col1,col2 from table1");
        ... // do something with rs
        rs.getStatement().close();
        rs = conn.createStatement().executeQuery("select col1,col2 from table2");
        ... // do somthing with rs
        rs.getStatement().close();
        rs = null;
    }catch(Exception e){
        throw e;
    }finally{
         if(rs != null){
             try{
                 rs.getStatement().close();
             }catch(SQLException se){
                 se.printStackTrace();
             }
         }
    }
}

两个问题:
1.我应该像那样重用结果集变量吗?
2.这样关闭结果集好吗?有什么更聪明的方法吗?

【问题讨论】:

标签: java jdbc


【解决方案1】:

看一下Spring JdbcUtils源码,它是这样关闭ResultSet的

public static void closeResultSet(ResultSet rs) {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException ex) {
            logger.trace("Could not close JDBC ResultSet", ex);
        } catch (Throwable ex) {
            // We don't trust the JDBC driver: It might throw
            // RuntimeException or Error.
            logger.trace("Unexpected exception on closing JDBC ResultSet", ex);
        }
    }
}

所以你的代码看起来像这样

    Statement st = conn.createStatement();
    try {
        ResultSet rs = st.executeQuery("select col1,col2 from table1");
        // do something
        closeResultSet(rs);
        rs = st.executeQuery("select col1,col2 from table2");
        // do something
        closeResultSet(rs);
    } finally {
        // close Statement
    }

虽然在我看来最好的方法是不要在低级别使用 JDBC,而是直接使用 Spring JDBC。它经过深思熟虑,将使您的代码简单可靠。

【讨论】:

  • 或者使用 Java 7 try-with-resources
猜你喜欢
  • 1970-01-01
  • 2011-09-30
  • 2021-12-21
  • 2011-01-31
  • 2013-10-02
  • 2010-10-06
  • 2011-10-28
  • 2010-09-10
  • 2011-10-11
相关资源
最近更新 更多