是否必须关闭用PHP中的PDO打开的SQL连接 [英] Do SQL connections opened with PDO in PHP have to be closed

查看:164
本文介绍了是否必须关闭用PHP中的PDO打开的SQL连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我仅使用PHP的内置MySQL函数在PHP中打开MySQL连接时,我将执行以下操作:

When I open a MySQL connection in PHP with just PHP's built-in MySQL functions, I do the following:

$link = mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
//queries etcetera
mysql_close($link);

当我打开与PDO的连接时,它看起来像这样:

When I open a connection with PDO, it looks like this:

$link = new PDO("mysql:dbname=$dbname;host=$servername",$username,$password);
//prepare statements, perform queries

是否必须像使用mysql_connect()mysql_close()一样显式关闭连接?如果没有,PHP如何知道我何时完成连接?

Do I have to explicitly close the connection like I do with mysql_connect() and mysql_close()? If not, how does PHP know when I'm done with my connection?

TIA.

推荐答案

使用$link = null让PDO知道它可以关闭连接.

Use $link = null to let PDO know it can close the connection.

PHP:PDO Connections&连接管理

成功连接到数据库后,PDO类的实例将返回到脚本.该连接在该PDO对象的生存期内保持活动状态.要关闭连接,您需要通过确保删除所有剩余的对该对象的引用来销毁该对象,方法是将NULL赋给保存该对象的变量.如果您未明确执行此操作,则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.

这篇关于是否必须关闭用PHP中的PDO打开的SQL连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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