现在我就是这样做的:
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.这样的结果集很好吗?任何更聪明的方式?
答案 0 :(得分: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。它通过思考,将使您的代码简单可靠。