Quantcast
Channel: 龙猫の笔记 » PDO
Viewing all articles
Browse latest Browse all 3

PDO unbuffered queries active 错误

$
0
0

PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

呃,上面的错误是什么东西?

举个栗子来说,如下的写法可能导致上述错误的发生:

$connection = new \PDO('mysql:dbname=test;host=127.0.0.1', 'username', 'password');
 
$stmt_one = $connection->prepare('SQL ONE');
$stmt_one->execute();
 
$stmt_two = $connection->prepare('SQL TWO');
$stmt_two->execute();
$stmt_two->fetchAll(PDO::FETCH_ASSOC);

也就是说,在同一个请求中使用了多个活跃的 PDOStatement 来操作数据时,有可能会遇到这个问题。
说可能是因为我遇到的情况是某些环境下没有问题,某些环境会出问题。嗯,总得来说是姿势不对。

按照错误中提示的修复方式经测试不是很管用,不管是在 prepare() 时指定 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY 属性,或者是注意 fetchAll()。

其实正确的解决办法网上已经有不少地方说明了,示例如下:

$stmt_one = $connection->prepare('SQL ONE');
$stmt_one->execute();
$stmt_one->closeCursor();
 
$stmt_two = $connection->prepare('SQL TWO');
$stmt_two->execute();
$stmt_two->fetchAll(PDO::FETCH_ASSOC);
$stmt_two->closeCursor();

即在使用完毕 PDOStatement 之后,使用 closeCursor 方法关闭游标。

关闭游标之后,该 PDOStatement 还能继续使用吗?
是的,是可以继续使用的:

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.

PDOStatement::closeCursor() is implemented either as an optional driver specific method (allowing for maximum efficiency), or as the generic PDO fallback if no driver specific function is installed.

PDOStatement::closeCursor

其实文档中也解释了为什么有些情况下没问题,有些情况下有问题,是数据库驱动的支持情况不同导致的。

相关文章:


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images