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

查看:23
本文介绍了尽管之后关闭了连接,但必须分别关闭 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天全站免登陆