2014-10-11 65 views
0

这里是我现在就做:最佳实践关闭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(); 
     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.这样很好的关闭结果集吗?任何更聪明的方式?

+1

考虑[这个答案](http://stackoverflow.com/a/321879/2711488),特别是。 – Holger 2014-10-11 12:10:08

回答

1

看看春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。它彻头彻尾地想通过并将使您的代码简单可靠。

+0

或者使用Java 7试用资源 – 2014-10-11 11:25:54