日期:2014-05-17  浏览次数:20658 次

mysql_connect后是不是非要mysql_close,是不是自动释放
大家伙们,PHP数据库连接是不是在页面执行完之后自己释放,即使不用mysql_close()也可以释放掉?
同理PDO连接到数据库后,是不是非要将PDO实例赋值为NULL,才能将PDO连接断掉?

在N久以前我查过资料,但己经模糊不清了,具说PHP处理每一个被请求的页面时,里面有MYSQL连接的,当页面处理完就立刻释放掉所有用到的资料。如:mysql_connect后的连接。这个说法对吗?PDO同理吗?

------解决方案--------------------
以下摘自PHP手册:
mysql_close() closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used.

Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

mysql_close对于非永久的connect不是必须的。
------解决方案--------------------
mysql_connect不一定需要强制用mysql_close关闭的
可以去看下php手册
上面说了mysql_connect() 函数打开非持久的 MySQL 连接。注释:脚本一结束,到服务器的连接就被关闭,除非之前已经明确调用 mysql_close() 关闭了。
也就是说,当脚本结束时,会自动关闭。
------解决方案--------------------
如果是mysql_pconnect就不一样了,需要自己用mysql_close关闭
------解决方案--------------------
通常不需要使用 mysql_close(),因为已打开的非持久连接会在脚本执行完毕后自动关闭,
------解决方案--------------------
探讨

如果是mysql_pconnect就不一样了,需要自己用mysql_close关闭

------解决方案--------------------
那mysql_connect打开的连接会在脚本执行完毕后由SQL服务器自动关闭喽?

這個是的

長鏈接的默認時效是8個小時.8個小時內你沒有操作那麼將斷開你的鏈接

wait_timeout=28800
------解决方案--------------------
CLI模式下,不论是mysql_connect还是mysql_pconnect,只要脚本退出,连接就被关闭。

CGI模式下,mysql_connect建立的连接,可以被mysql_close关闭;也可以不手工关闭,而等待请求结束后自动释放。但是mysql_pconnect建立的连接,无法被mysql_close关闭,请求结束后也不会释放。

mysql_pconnect被关闭的情况,我知道有:
1、空闲时间超过了mysqld的wait_timeout(单位是秒)
2、web server进程退出,以nginx+php-fpm为例,就是一个php-fpm进程结束
------解决方案--------------------
手册上说的比较权威

http://cn.php.net/manual/zh/pdo.connections.php

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
------解决方案--------------------
去年无聊时研究过mysql_pconnect,认真写了篇博文,你可以看看
http://www.cnblogs.com/funlake/archive/2011/09/08/2171822.html