gpt4 book ai didi

php - 如果语句对象未设置,是否需要调用 PDOStatement::closeCursor() ?

转载 作者:IT王子 更新时间:2023-10-29 00:34:27 24 4
gpt4 key购买 nike

我使用基于 Mysql 的 PDO 连接PDOStatement (::prepare(); ::execute() ) 并且我已经运行了一些来自以前的开发人员的代码,这些代码在方法中使用 PDOStatement::closeCursor()

无论如何,该语句在函数末尾未设置:

public function fooBar($identifier)
{
...
/** @var $dbc PDO */
$dbc = $conn->getConnection();
$stmt = $dbc->prepare('SELECT orderType, orderComment, payload FROM cart WHERE identifier = :identifier');
$stmt->execute(array('identifier' => $identifier));

$stmt->setFetchMode(PDO::FETCH_OBJ);
$cart = $stmt->fetch();
$stmt->closeCursor();

...

return $result;
}

在我的心智模型中,我会说 PDOStatement 无论如何都在这里被清除,因为我希望对象负责这个内务处理(封装基础知识)。因此,调用 PDOStatement::closeCursor() 对我来说看起来很多余,尤其是,因为这可能不是这里想要的:因为语句不会被重复使用,所以我不需要完全关闭光标。

side-note: this code is exemplary, in the real code, there is even an exception thrown after $stmt->execute(...) if the row-count is not one (1).

Stackoverflow 上的现有 Material

Charles commmented back in May 2011 问题中的 pdo free result :

Not just some drivers -- some settings provided by drivers require closing the result set before firing off another query, like turning off MySQL's PDO::MYSQL_ATTR_USE_BUFFERED_QUERY. Thankfully you can call closeCursor and it will successfully do nothing when it doesn't need to take action. Otherwise simply unsetting the variable containing the statement handle will clean up.

另一个问题 When should I use closeCursor() for PDO statements? 没有公认的答案,我对此并不感到奇怪,因为它都是空洞的。

Reusing PDO statement var crashes the process 中有一个 a comment made 取消设置变量不会排除所有错误(内存损坏错误):

[...] I did try to unset the statement var before reassigning it but it didn't help. [...]

但是我不知道这是否也适用于范围将消失的局部变量。我也不使用 mod_php 作为 SAPI。

相关漏洞 Material

最佳答案

pdo_mysql_stmt_dtor()运行与 pdo_mysql_stmt_cursor_closer() 相同的清理操作, 因此只要声明对象显式取消设置或超出范围,就会始终执行操作。

因此,如果语句即将被销毁,则严格来说不必调用 closeCursor()。就我个人而言,无论如何我都会这样做,因为我希望明确表示可读性,但这归结为个人风格偏好。

根据上面的引用资料,这只能肯定地说关于 PDO_mysql - 对于其他驱动程序,这可能不成立。

关于php - 如果语句对象未设置,是否需要调用 PDOStatement::closeCursor() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24570784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com