php - 我应该在获取后手动关闭数据库连接和语句的游标吗?

标签 php doctrine-orm dbal

我正在使用 Silex 和 Doctrine DBAL 构建一些东西使用 Mysql 数据库。

我想知道在一个人完成后关闭语句和数据库连接的游标是否被认为是最佳实践。例如:

$sql = '
    SELECT
        `id`, `userid`, `name`, `content` 
    FROM 
        `pages` p 
    WHERE 
        p.`userid` in (?)'; 

$stmt = $conn->executeQuery(
    $sql,
    [$userIds],
    [\Doctrine\DBAL\Connection::PARAM_INT_ARRAY]
);

$rows = $stmt->fetchAll();

$stmt->closeCursor();

$conn->close();

我找不到这方面的任何例子。 Silex 和 Doctrine 文档都不使用这些语句,但它们的存在是有原因的,对吗?

最佳答案

$stmt->closeCursor() appears只是包装PDOStatement::closeCursor()并允许您在需要时重新执行查询:

PDOStatement::closeCursor() frees up the connection to the server so that other SQL statements may be issued, but leaves the statement in a state that enables it to be executed again.

This method is useful for database drivers that do not support executing a PDOStatement object when a previously executed PDOStatement object still has unfetched rows. If your database driver suffers from this limitation, the problem may manifest itself in an out-of-sequence error.

在您发布的示例中,您没有执行多个查询,而是在查询后立即关闭连接。因此,调用它是没有好处的。如果您真的关心内存使用情况,将$stmt 设置为null 应该会更有效。

Connection::close() appears只是将对象上的连接设置为空:

/**
 * Closes the connection.
 *
 * @return void
 */
public function close()
{
    $this->_conn = null;
    $this->_isConnected = false;
}

它释放了一些内存,因此比调用它更好。但是我希望好处可以忽略不计,因为它会在脚本终止时关闭。

关于php - 我应该在获取后手动关闭数据库连接和语句的游标吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32912309/

相关文章:

mysql - symfony2主义2 : in which cases do we need to lock a database table/row?

mysql - Doctrine orWhere 用于多列

php - 使用 Doctrine DBAL 一次删除多行,是否可能?

php - Laravel 卡住了最后一个在论坛发帖的用户

php - Symfony 在哪里初始化 Doctrine 的默认事务隔离级别?

PostgreSQL 咨询锁不适用于 Doctrine 的 DBAL

php - 执行多个查询时的 Doctrine (DBAL) 错误处理

php - 创建一个独特且看似随机的 5 个字符的字符串

php - 输入类型的文件不起作用:ajax到php

php - 如何转义 MYSQL 查询中的引号?