我正在使用 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/