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

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

问题描述

当我不需要在我的程序中使用这些ResultSet和Connection的实例时,为什么我应该在两者上调用.close()方法?


解决方案

这里有两个问题:



数据库连接



保持数据库连接打开会消耗数据库上的资源;它使用内存和数据库配置为具有最大数量的连接,因此增加了可能性的连接断开。还保持会话的状态,所以你可以遇到麻烦的锁被意外地超出了他们想要的范围。



从积极的角度来看,预编译语句保持编译并可以使用,因此如果正确编写和使用SQL,您可以通过重复使用预编译语句获得显着的性能优势。



此外,获取连接是非常昂贵的,因此连接池。这些连接将打开,但客户端获得连接,使用它们,然后在完成后将其释放回池。



结果集



如果您不 commit (关闭然后结果集),保持结果集打开也将保持某些锁打开,因此根据您的应用程序,你可以快速打击僵局或严重的生机问题。无论您是否保持连接打开,始终尽快关闭结果集,以尽可能多地将资源发回数据库。


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 ?

解决方案

There are two questions here:

Database connections

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.

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.

Result set

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天全站免登陆