使用PHP5.5时,我注意到在使用连接执行语句之后无法关闭PDO连接。
例如:
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$dbh = null;很好地关闭了连接。但我无法在此关闭以下连接:
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("select * from someTable where 1<>0");
$stmt->execute();
$dbh = null;发布于 2014-09-22 22:27:33
您可以在这里的PHP中看到与此相关的注释,http://php.net/manual/en/pdo.connections.php#114822。简而言之,您需要将语句和连接设置为null。
$stmt = null;
$dbh = null; 发布于 2014-09-22 22:25:25
我在这里做了一个合理的猜测,即$stmt也间接引用了$dbh,因为它需要它来获取数据和其他东西。也试着取消这个。
发布于 2017-11-10 16:21:32
您可以包装数据库对象,并创建一个关闭语句的__destruct方法。小心点,我没有测试下面的代码。
class MyPDO extends \PDO
{
protected $db;
protected $stm;
public function __construct($conn_string,$user,$password)
{
$opts = [
\PDO::ATTR_PERSISTENT => true // careful, if connection fails to close, "has gone away" may appear on the next connection.
, \PDO::MYSQL_ATTR_FOUND_ROWS => true
, \PDO::ATTR_EMULATE_PREPARES => false
];
$this->db = new \PDO($conn_string, $user, $password, $opts);
}
public function prepare($query,$options = [])
{
$this->stm = $this->db->prepare($query,$options);
return $this->stm;
}
public function close()
{
if(is_object($this->stm))
{
$this->stm->closeCursor();
}
$this->stm = null;
$this->db = null;
}
public function __destruct()
{
$this->close();
}
}
$dbh = new MyPDO(...);
$stmt = $db->prepare(...);
$stmt->execute();
$dbh = null; // this should call the __destruct method, and ensure everything is closed properlyhttps://stackoverflow.com/questions/25983988
复制相似问题