与MySQLi相比,PDO只是一个相当简单的问题.
使用MySQLi,要关闭连接,您可以执行以下操作:
$this->connection->close();
Run Code Online (Sandbox Code Playgroud)
但是对于PDO,它声明您使用以下命令打开连接:
$this->connection = new PDO();
Run Code Online (Sandbox Code Playgroud)
但要关闭您设置的连接null.
$this->connection = null;
Run Code Online (Sandbox Code Playgroud)
这是正确的,这实际上是否会释放PDO连接?(我知道它确实设置为null.)我的意思是MySQLi你必须调用一个函数(close)来关闭连接.PDO是否易于= null断开?或者是否有关闭连接的功能?
Kie*_*ran 133
根据文档你是对的(http://php.net/manual/en/pdo.connections.php):
该连接在该PDO对象的生命周期内保持活动状态.要关闭连接,您需要通过确保删除对它的所有剩余引用来销毁对象 - 您可以通过为保存对象的变量赋值来执行此操作.如果您没有明确地执行此操作,PHP将在脚本结束时自动关闭连接.
请注意,如果将PDO对象初始化为持久连接,则不会自动关闭连接.
小智 37
$conn=new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
// If this is your connection then you have to assign null
// to your connection variable as follows:
$conn=null;
// By this way you can close connection in PDO.
Run Code Online (Sandbox Code Playgroud)
Jda*_*ern 15
它不仅仅是将连接设置为空。这可能是文档所说的,但这不是 mysql 的真相。连接会保持一段时间(我听说过 60 年代,但从未测试过)
如果您想在此处查看完整说明,请参阅有关连接https://www.php.net/manual/en/pdo.connections.php#114822 的此评论
要强制关闭连接,您必须执行以下操作
$this->connection = new PDO();
$this->connection->query('KILL CONNECTION_ID()');
$this->connection = null;
Run Code Online (Sandbox Code Playgroud)
我创建了一个派生类来拥有更多的自记录指令而不是$conn=null;.
class CMyPDO extends PDO {
public function __construct($dsn, $username = null, $password = null, array $options = null) {
parent::__construct($dsn, $username, $password, $options);
}
static function getNewConnection() {
$conn=null;
try {
$conn = new CMyPDO("mysql:host=$host;dbname=$dbname",$user,$pass);
}
catch (PDOException $exc) {
echo $exc->getMessage();
}
return $conn;
}
static function closeConnection(&$conn) {
$conn=null;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以在以下之间调用我的代码:
$conn=CMyPDO::getNewConnection();
// my code
CMyPDO::closeConnection($conn);
Run Code Online (Sandbox Code Playgroud)