必须单独关闭JDBC结果集和语句,但之后关闭连接? [英] Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

查看:267
本文介绍了必须单独关闭JDBC结果集和语句,但之后关闭连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据说在使用后关闭所有JDBC资源是一个好习惯。但是如果我有以下代码,是否需要关闭Resultset和Statement?

It is said to be a good habit to close all JDBC resources after usage. But if I have the following code, is it necessary to close the Resultset and the 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) {};
}

问题是连接的关闭是否完成了工作或者是否已经离开一些正在使用的资源。

The question is if the closing of the connection does the job or if it leaves some resources in use.

推荐答案

你所做的是完美和非常好的做法。

What you have done is perfect and very good practice.

我说它的良好做法的原因......例如,如果由于某种原因你使用原始类型的数据库池并且你调用 connection.close(),连接将返回到池中, ResultSet / Statement 将永远不会被关闭然后你会遇到很多不同的新问题!

The reason I say its good practice... For example, if for some reason you are using a "primitive" type of database pooling and you call connection.close(), the connection will be returned to the pool and the ResultSet/Statement will never be closed and then you will run into many different new problems!

所以你不能总是指望 connection.close()清理。

So you can't always count on connection.close() to clean up.

我希望这会有所帮助:)

I hope this helps :)

这篇关于必须单独关闭JDBC结果集和语句,但之后关闭连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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