为什么要在 ResultSet 和 Connection 实例上调用 close()? [英] Why should I call close() on a ResultSet and Connection instance?

查看:24
本文介绍了为什么要在 ResultSet 和 Connection 实例上调用 close()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我不再需要在我的程序中使用这些 ResultSet 和 Connection 的实例时,我为什么要对它们都调用 .close() 方法?

When I don't need to use instances of those ResultSet and Connection anymore in my program, why should I call the .close() method on both of them ?

不这样做有什么危险(如果有的话)?

What are the dangers (if any) of not doing so ?

推荐答案

这里有两个问题:

保持数据库连接打开会消耗数据库上的资源;它使用内存,并且数据库配置为具有最大连接数,因此您增加连接用完的可能性.会话的状态也会得到维护,因此您可能会遇到意外持有超出其预期范围的锁的麻烦.

Holding a database connection open consumes resources on the database; it uses memory and databases are configured to have a maximum number of connections, so you increase to likelihood of running out of connections. Also the state of the session is maintained, so you can run into trouble with locks being accidentally held beyond their intended scope.

从积极的方面来说,预编译语句保持编译状态并可供使用,因此,如果您正确编码和使用 SQL,您可以通过重用预编译语句获得显着的性能优势.但是,这样做可能会使您的代码复杂化,因此建议您小心.

On the positive side, prepared statements stay compiled and ready for use, so if you code and use your SQL correctly, you can gain significant performance benefits from reusing prepared statements. However, doing so may complicate your code and care is advised.

此外,获取连接的成本非常高,这就是存在 连接池 的原因.这些使连接保持打开状态,但客户端获取连接,使用它们,然后在完成后将它们释放回池中.

Also, obtaining a connection is quite expensive, so that's why connection pools exist. These leave the connections open, but the client gets connections, uses them, then releases them back to the pool when done.

如果您不commit(然后关闭结果集),保持结果集打开也会保持某些锁打开,因此根据您的应用程序,您可以快速遇到死锁或严重的活跃度问题.无论您是否保持连接打开,请始终尽快关闭您的结果集,以便将尽可能多的资源释放回数据库.

Holding result sets open will also hold certain locks open if you don't commit (which closes then result set), thus depending on your application, you can quickly hit deadlocks or severe liveliness issues. Regardless of whether you hold connections open, always close your result sets as soon as possible to release as much resource back to the database as you can.

这篇关于为什么要在 ResultSet 和 Connection 实例上调用 close()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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