简体   繁体   English

PHP MySQL数据库连接

[英]PHP MySQL Database Connection

是否有必要在执行查询(和其他数据库操作)后显式关闭数据库连接?

No, php does that automatically. 不,php会自动执行此操作。 You could call it "good programming practice" to clean up (aka close the connection) though. 你可以称之为“良好的编程习惯”来清理(也就是关闭连接)。

Generally, only close it after you have finished the database for that entire page. 通常,只有在完成整个页面的数据库后才关闭它。 Also, depending on the API you are using to handle the database, most ones you should be using now (such as PDO ) are implemented via Objects, so the destructor will automatically handle closing it at the end if needed. 此外,根据您用来处理数据库的API,您现在应该使用的大多数API(例如PDO )都是通过Objects实现的,因此析构函数会在需要时自动处理它的结束。

Nope, unless you're sure you've finished communicating with the database for the script run. 不,除非您确定已完成与脚本运行的数据库通信。 Even then, you don't need to close it explicitly at all as PHP does that automatically after your script finishes executing, unless you're using mysql_pconnect() to connect to your database. 即使这样,您也不需要显式地关闭它,因为PHP会在脚本完成执行后自动执行,除非您使用mysql_pconnect()连接到您的数据库。

even though php does it automatically I can tell as much as if we didnt do it on our site, our db server would reach max_connections really really fast. 即使php自动执行,我也可以告诉我们在我们的网站上没有这样做,我们的数据库服务器会非常快地达到max_connections。 So its very good practice. 所以这是非常好的做法。

Actually I would structure code like this 实际上我会像这样构造代码

open conn make all queries close con open conn使所有查询都关闭

rest of the code 其余的代码

Because then slow devices wont make your connections hang. 因为慢速设备不会让你的连接挂起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM