据说在使用后关闭所有JDBC资源是一个好习惯.但是,如果我有以下代码,是否有必要关闭Resultset和Statement?
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = // Retrieve connection
stmt = conn.prepareStatement(// Some SQL);
rs = stmt.executeQuery();
} catch(Exception e) {
// Error Handling
} finally {
try { if (rs != null) rs.close(); } catch (Exception e) {};
try { if (stmt != null) stmt.close(); } catch (Exception e) {};
try { if (conn != null) conn.close(); } catch (Exception e) {};
}
Run Code Online (Sandbox Code Playgroud)
问题是连接的关闭是否完成了工作,或者是否使用了一些资源.
考虑一下代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
上面没有编译,因为都PreparedStatement.close()和ResultSet.close()抛出java.sql.SQLException.那么我要在finally子句中添加一个try/catch块吗?或者将close语句移动到try子句中?或者只是不打扰打电话?