与MySQLi相比,这只是一个关于PDO的相当简单的问题。
使用MySQLi,您可以执行以下操作来关闭连接:
$this->connection->close();
但是,对于PDO,它说明您使用以下命令打开连接:
$this->connection = new PDO();
但是要关闭连接,您需要将其设置为null
。
$this->connection = null;
这是正确的吗?这实际上会释放PDO连接吗?(我知道它是这样的,因为它设置为null
。)我的意思是,在MySQLi中,你必须调用一个函数(close
)来关闭连接。PDO和= null
一样容易断开连接吗?或者是否有关闭连接的功能?
发布于 2015-06-09 11:15:55
$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.
发布于 2019-08-16 00:02:46
这不仅仅是将连接设置为空。文档可能是这么说的,但mysql并非如此。这种连接还会持续一段时间(我听说过60年代,但从未测试过)
如果您想在这里查看完整的解释,请参阅connections https://www.php.net/manual/en/pdo.connections.php#114822上的评论
要强制关闭连接,您必须执行以下操作
$this->connection = new PDO();
$this->connection->query('KILL CONNECTION_ID()');
$this->connection = null;
发布于 2017-05-24 08:18:29
我创建了一个派生类来代替$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;
}
}
这样我就可以在以下代码之间调用我的代码:
$conn=CMyPDO::getNewConnection();
// my code
CMyPDO::closeConnection($conn);
https://stackoverflow.com/questions/18277233
复制相似问题