在哪里关闭 java PreparedStatements 和 ResultSets? [英] Where to close java PreparedStatements and ResultSets?

查看:34
本文介绍了在哪里关闭 java PreparedStatements 和 ResultSets?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑代码:

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();
}

以上不能编译,因为 PreparedStatement.close()ResultSet.close() 都抛出一个 java.sql.SQLException.那么我要在 finally 子句中添加一个 try/catch 块吗?或者将 close 语句移到 try 子句中?或者只是不想打扰关闭?

The above does not compile, because both PreparedStatement.close() and ResultSet.close() throw a java.sql.SQLException. So do I add a try/catch block to the finally clause? Or move the close statements into the try clause? Or just not bother calling close?

推荐答案

对于文件 I/O,我通常会在 finally 块中添加一个 try/catch.但是,您必须注意不要从 finally 块中抛出任何异常,因为它们会导致原始异常(如果有)丢失.

For file I/O, I generally add a try/catch to the finally block. However, you must be careful not to throw any exceptions from the finally block, since they will cause the original exception (if any) to be lost.

有关关闭数据库连接的更具体示例,请参阅这篇文章.

See this article for a more specific example of database connection closing.

这篇关于在哪里关闭 java PreparedStatements 和 ResultSets?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆