我什么时候应该关闭数据库连接?

发布于 2024-08-21 06:44:39 字数 22 浏览 2 评论 0原文

PHP脚本中是否必须关闭连接?

Is it a must to close the connection in PHP script?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

独守阴晴ぅ圆缺 2024-08-28 06:44:39

根据数据库服务器的配置,同时打开的连接数可能受到限制。

因此,如果您的脚本:

  • 执行一些查询
  • ,然后执行一些长时间计算,而不再执行任何查询,那么

在完成所有查询后关闭连接可能会很有趣,并且仅在需要时才打开连接。

不过,请注意,无论如何,当脚本结束时连接都会关闭;这意味着,如果您没有 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 :

  • does some queries
  • and, then, does some long calculations without doing any query anymore

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 :

  • Open the connection on the first query (Which means no connection is opened if no query is sent)
  • Never close the connection : as my pages asre built using lots of components, I have no way of knowing for sure that the connection won't be needed anymore.
棒棒糖 2024-08-28 06:44:39

是的。一般规则是:尽可能晚地打开连接,并尽快关闭它们。在大多数现代系统/环境中,连接都是池化的,因此不断打开和关闭它们不会出现问题(性能影响)。

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.

吃兔兔 2024-08-28 06:44:39

当 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文