首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一旦语句被执行,pdo连接就不会关闭

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

Stack Overflow用户
提问于 2014-09-22 22:22:20
回答 3查看 499关注 0票数 1

使用PHP5.5时,我注意到在使用连接执行语句之后无法关闭PDO连接。

例如:

代码语言:javascript
复制
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$dbh = null;

很好地关闭了连接。但我无法在此关闭以下连接:

代码语言:javascript
复制
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("select * from someTable where 1<>0");
$stmt->execute();
$dbh = null;
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-09-22 22:27:33

您可以在这里的PHP中看到与此相关的注释,http://php.net/manual/en/pdo.connections.php#114822。简而言之,您需要将语句和连接设置为null。

代码语言:javascript
复制
$stmt = null;
$dbh = null; 
票数 2
EN

Stack Overflow用户

发布于 2014-09-22 22:25:25

我在这里做了一个合理的猜测,即$stmt也间接引用了$dbh,因为它需要它来获取数据和其他东西。也试着取消这个。

票数 1
EN

Stack Overflow用户

发布于 2017-11-10 16:21:32

您可以包装数据库对象,并创建一个关闭语句的__destruct方法。小心点,我没有测试下面的代码。

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25983988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档