Java 关闭jdbc结果集的最佳实践

Java 关闭jdbc结果集的最佳实践,java,jdbc,Java,Jdbc,我现在是这样做的: 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(

我现在是这样做的:

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.这样结束结果集好吗?有更聪明的方法吗?

看看SpringJDBCutils源代码,它用这种方法关闭结果集

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,而是直接使用SpringJDBC。它经过深思熟虑,将使您的代码简单可靠。

或者使用Java 7,尤其是resourcesConsider。