fro*_*die 25 java connection jdbc prepared-statement
PreparedStatement在JDBC中使用时,我应该关闭第PreparedStatement一个还是第Connection一个?我刚刚看到一个代码示例,其中Connection首先关闭它,但在我看来更合乎逻辑地关闭第PreparedStatement一个.
是否有标准的,可接受的方式来做到这一点?有关系吗?关闭Connection也会导致PreparedStatement关闭,因为PreparedStatement它与Connection对象直接相关吗?
Bri*_*new 40
该声明.我希望你关闭(按顺序)
(并检查沿途的空值!)
即以与开启顺序相反的顺序关闭.
如果你使用Spring JdbcTemplate(或类似的),那么它将为你照顾.或者,您可以使用Apache Commons DbUtils和DbUtils.close()or DbUtils.closeQuietly().
应该完成以下程序(按顺序)
ResultSetPreparedStatementConnection.此外,建议关闭所有与JDBC相关的对象finally以保证闭包.
//Do the following when dealing with JDBC. This is how I've implemented my JDBC transactions through DAO....
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = ....
ps = conn.prepareStatement(...);
//Populate PreparedStatement
rs = ps.executeQuery();
} catch (/*All relevant exceptions such as SQLException*/Exception e) {
logger.error("Damn, stupid exception: " , e);
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
logger.error(e.getMessage(), e.fillInStackTrace());
}
}
if (ps != null) {
try {
ps.close();
ps = null;
} catch (SQLException e) {
logger.error(e.getMessage(), e.fillInStackTrace());
}
}
try {
if (conn!= null && !conn.isClosed()){
if (!conn.getAutoCommit()) {
conn.commit();
conn.setAutoCommit(true);
}
conn.close();
conn= null;
}
} catch (SQLException sqle) {
logger.error(sqle.getMessage(), sqle.fillInStackTrace());
}
}
Run Code Online (Sandbox Code Playgroud)
您可以看到我已检查我的对象是否为空并且是否为连接,请首先检查连接是否未自动更新.许多人未能检查它并意识到事务尚未提交给DB.
| 归档时间: |
|
| 查看次数: |
24766 次 |
| 最近记录: |