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

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

问题描述

考虑代码:

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子句中?或者只是不打扰调用close?

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和ResultSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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