我什么时候应该关闭数据库连接?
PHP脚本中是否必须关闭连接?
Is it a must to close the connection in PHP script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
PHP脚本中是否必须关闭连接?
Is it a must to close the connection in PHP script?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
根据数据库服务器的配置,同时打开的连接数可能受到限制。
因此,如果您的脚本:
在完成所有查询后关闭连接可能会很有趣,并且仅在需要时才打开连接。
不过,请注意,无论如何,当脚本结束时连接都会关闭;这意味着,如果您没有 wya 来确保已完成查询,则无需需要关闭连接:保持连接打开状态允许您在任何时候执行一些额外的查询必要的。
(当您的页面是使用多个不同且独立的组件构建的,并且这些组件都容易进行数据库查询时,这一点尤其正确)
对于我编写的应用程序,我通常:
Depending on the configuration of your DB server, there is a limit on the possible number of connections opened to it at the same time.
So, if your script :
It can be interesting to close the connection after having done all your queries -- and to only open the connection when it's becoming needed.
Still, note that connections are closed when the script ends, anyway ; which means that if you don't have a wya to be sure that you have finished doing queries, you don't need to close the connection : keeping it opened allows you to do some additionnal queries whenever it's necessary.
(This is particularly true is your pages are built using several distinct and independant components, that are all susceptible to do DB queries)
For the applications I write, I generally :
是的。一般规则是:尽可能晚地打开连接,并尽快关闭它们。在大多数现代系统/环境中,连接都是池化的,因此不断打开和关闭它们不会出现问题(性能影响)。
Yes, it is. As a general rule is this: open connections as late as possible, and close them as soon as possible. In most modern systems/environments connections are pooled, so there's no problem (performance hit) in constantly opening and closing them.
当 php scrip 完成运行时,所有对象、变量甚至数据库连接都会丢失。否则使用新的数据库连接对象。但根据经验,最好打开连接并在不需要时关闭它。
When the php scrip finishes running, all objects, variables are lost even the db connection.else with the new db connection object. But as rule of thumb, it is better to open connection and close it when you don't need it.