PHP mySQL-何时是断开数据库连接的最佳时间? [英] PHP mySQL - When is the best time to disconnect from the database?

查看:121
本文介绍了PHP mySQL-何时是断开数据库连接的最佳时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用惰性连接来连接数据库对象中的数据库.这基本上意味着,在处理完第一个查询之前,它不会调用mysql_connect(),并且此后它随后将跳过重新连接.

I use lazy connection to connect to my DB within my DB object. This basically means that it doesn't call mysql_connect() until the first query is handed to it, and it subsequently skips reconnecting from then on after.

现在,我的数据库类中有一个名为disconnectFromDB()的方法,该方法几乎调用了mysql_close()并设置了$_connected = FALSE(因此query()方法将知道再次连接到数据库).应该在每个查询之后(作为私有函数)还是通过对象在外部调用此方法...因为我在想类似的东西(代码仅是示例)

Now I have a method in my DB class called disconnectFromDB() which pretty much calls mysql_close() and sets $_connected = FALSE (so the query() method will know to connect to the DB again). Should this be called after every query (as a private function) or externally via the object... because I was thinking something like (code is an example only)

$students = $db->query('SELECT id FROM students');

$teachers = $db->query('SELECT id FROM teachers');

现在,如果它在每次查询后都关闭,那么这会减慢很多速度,而不是我将这行添加到末尾

Now if it was closing after every query, would this slow it down a lot as opposed to me just adding this line to the end

$db->disconnectFromDB();

还是我应该在页面末尾的上方添加该行?

Or should I just include that line above at the very end of the page?

两者都有哪些优点/缺点?在您的情况下,哪种方法最有效?忘记关闭mySQL连接真的有什么不对劲,除了会损失一点性能之外?

What advantages/disadvantages do either have? What has worked best in your situation? Is there anything really wrong with forgetting to close the mySQL connection, besides a small loss of performance?

感谢您抽出宝贵的时间来回答.

Appreciate taking your time to answer.

谢谢!

推荐答案

据我所知,除非您使用持久连接,否则您的MySQL连接将在页面执行结束时关闭.

As far as I know, unless you are using persistent connections, your MySQL connection will be closed at the end of the page execution.

因此,您调用断开连接将不会添加任何内容,并且由于您执行的是惰性连接,如果您或其他开发人员出错并在错误的时间断开连接,则可能会导致创建第二个连接.

Therefore, you calling disconnect will add nothing and because you do the lazy connection, may cause a second connection to be created if you or another developer makes a mistake and disconnects at the wrong time.

鉴于此,我只允许我的连接自动关闭.您的页面应该能够快速执行,因此在短时间内保持连接不会造成任何问题.

Given that, I would just allow my connection to close automatically for me. Your pages should be executing quickly, therefore holding the connection for that small amount of time shouldn't cause any problems.

这篇关于PHP mySQL-何时是断开数据库连接的最佳时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆