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

查看:42
本文介绍了在 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天全站免登陆