PDO General error: 2014 Cannot execute queries while other unbuffered queries are active when trying to LOCK TABLES

PDO General error: 2014 Cannot execute queries while other unbuffered queries are active when trying to LOCK TABLES

我正在将某人的旧代码从使用 mysql() 更新为使用 PDO。在一个地方,他们有一些 LOCK TABLES 命令来防止两个用户同时访问相同的数据。当 运行 LOCK TABLESPDO 抛出 "General Error: 2014 Cannot execute queries while other unbuffered queries are active".

我做了一些测试代码来消除其他变量。系统运行于 Ubuntu 18 / PHP 7.2 / MySQL 5.7.27:

try {
    $_DB=new PDO("mysql:host=".DBHOST.";dbname=".DBNAME.";charset=utf8", DBUSER, DBPASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", PDO::ATTR_TIMEOUT => "5",  PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_DIRECT_QUERY=>false,PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>true ));      

    // This gives the 2014 error. Any queries following this get the 2014 error.
    // Any queries before this work fine.
    $_DB->query("LOCK TABLES Inspections WRITE");

    $_DB->query("UNLOCK TABLES");
}
catch (Exception $e) {
    logError("Error : ".$e->getMessage());           
    // per @dharman's comment 
    //exit();
    throw($e);
}

我也尝试在 LOCK TABLES 之前添加 $_DB->beginTransaction 并在 UNLOCK TABLES 之后添加 $_DB->commit,但我仍然得到同样的错误。

我尝试了 ATTR_EMULATE_PREPARESMYSQL_ATTR_USE_BUFFERED_QUERY 的各种组合,但似乎没有任何区别。

您应该使用 exec() 而不是 query()exec() 不期望任何 return 值,这正是 LOCK TABLES 所需要的。

$pdo->exec("LOCK TABLES Inspections WRITE");