为什么这个带有准备好的语句的 SQLite 事务不起作用?

Why does this SQLite transaction with prepared statements not work?

我正在尝试结合 SQLite 事务和准备好的语句以获得数千条记录的最佳插入速度。但是,所有插入的行都是空的。

在插入之前打印变量表明它们具有正确的数据并且没有错误。

$db->beginTransaction();
$insert_stmt = $db->prepare("INSERT INTO `table` VALUES (:id, :value2, :value3, :value4)");
$insert_stmt->bindValue(":id", $id);
$insert_stmt->bindValue(":value2", $value2);
$insert_stmt->bindValue(":value3", $value3);
$insert_stmt->bindValue(":value4", $value4);

foreach ($records as $record)
{
  $id = $record["id"];
  $value2 = $record["value2"];
  $value3 = $record["value3"];
  $value4 = $record["value4"];
  $insert_stmt->execute();
  print_r($db->errorInfo()); // print errors
}

$db->commit();
  1. 代码有什么问题?
  2. 如何获得更好的输出?例如,在执行之前打印准备好的语句,以查看它是否有问题。

您必须将 bindValue 调用放入循环中。

当您执行 bindValue 时,这些值会被复制到语句中。之后你曾经做过的变量发生了什么都没有关系。