开发者

When should I close the db connection?

开发者 https://www.devze.com 2022-12-19 17:34 出处:网络
Is i开发者_StackOverflowt a must to close the connection in PHP script?Depending on the configuration of your DB server, there is a limit on the possible number of connections opened to it at the same

Is i开发者_StackOverflowt a must to close the connection in PHP script?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号