一旦语句被执行,pdo连接就不会关闭

时间:2014-09-22 22:22:21

标签: php pdo

使用PHP 5.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;

3 个答案:

答案 0 :(得分:2)

您可以在此处http://php.net/manual/en/pdo.connections.php#114822的PHP文档中查看有关此内容的相关说明。简而言之,您需要将语句和连接设置为null。

$stmt = null;
$dbh = null; 

答案 1 :(得分:1)

我在这里做了一个有根据的猜测,$stmt也有$dbh的间接引用,因为它需要它来获取数据和内容。尝试将其归零。

答案 2 :(得分:0)

您可以包装数据库对象,并创建一个__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 properly