问题描述
我一直认为关闭数据库连接总是一个好习惯,无论数据库/ORM如何,例如mysql_close()、Propel::close()等.
I was always in assumption that it is always a good practice to close database connection, regardless of database/ORM, like mysql_close(), Propel::close() etc.
参考我的另一个问题和在互联网上进行的其他一些研究中,我发现了一张令人惊讶的面孔,大多数人建议关闭连接并不重要,因为连接总是在请求后关闭.
With reference to one of my other question and some other research on Internet, I came to know a surprising face that most people recommends it doesn't really matter if you close connection as connection always gets closed after the request.
但是,我发现这些答案很难消化.原因是,为什么所有的 DB lib、ORM 都提供 close 方法?如果它存在,在每个 ORM/lib 中,一定有一些好的用途.
However I'm finding those answers little difficult to digest. Reason is, why all DB lib, ORM provide close method? If it is there, in every ORM/lib, there must be some good use of it.
有人可以解释一下在什么情况下,我们应该使用close方法来关闭数据库连接?&如果这些方法根本没有用,为什么它们存在于所有 db libs/ORM 中?
Can someone please shed some light on under what circumstances, we should use close method to close DB connection? & if these methods are not useful at all, why they are present there in all db libs/ORM?
编辑
我的结论
这是 Bondye 和 Fluffeh 之间的一次很好的讨论,它消除了我对使用连接关闭的疑虑.感谢他们俩.
It was a good discussion between Bondye and Fluffeh and it cleared my doubts about use of connection closing. Thanks to both of them.
- 如果您的脚本预计持续时间少于 100 毫秒,请不要费心关闭连接.
- 但是:如果脚本预计会持续更长时间,并且在最后一次数据库操作和脚本关闭之间有一段时间,请通过调用 *close() 为其他人释放连接.
我真的很难接受一个答案,因为两个答案都正确.只需接受所有评论的答案,使其保持在首位.但对两个正确答案 +1.
It is really very difficult for me to accept one answer as both answer are correct on its place. Just accepting answer with all comments so that it remain on top. But +1 to both correct answers.
推荐答案
通常不需要使用 mysql_close()
,因为非持久打开的链接会在脚本执行结束时自动关闭.
Using mysql_close()
isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
释放资源
感谢 PHP 4 的 Zend 引擎引入的引用计数系统,自动检测到不再引用它的资源,并被垃圾收集器释放.因此,很少需要手动释放内存.
Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.
希望这对您有更多帮助.
Hope this helps you more.
(来源)
mysql_close()
的目的也是为了节省计算机资源,但是使用它的另一个关键原因是因为 MySQL 服务器可以接受的连接数量有限,如果你有几个客户端无缘无故地保持连接打开,那么服务器很可能需要拒绝其他等待的客户端.这自然是一件坏事,因此,与 mysql_free_result()
一样,如果您认为上次使用数据库之间会有一段时间,最好调用 mysql_close()
和你的脚本结束.
The purpose of mysql_close()
is also to save computer resources, but another key reason for using it is because there is a limited number of connections that a MySQL server can accept, and if you have several clients holding connections open for no reason then the server may well need to turn away other, waiting clients. Naturally this is a bad thing, so, as with mysql_free_result()
, it is good to call mysql_close()
if you think there will be some time between your last database use and your script ending.
这篇关于php中关闭数据库连接的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!