在哪里关闭java PreparedStatements和ResultSet?

编程入门 行业动态 更新时间:2024-10-20 04:10:25
本文介绍了在哪里关闭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?

本文发布于:2023-10-18 11:00:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504045.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:java   PreparedStatements   ResultSet

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!