抱歉这个初学者问题,我不是 PHP 开发人员,但现在我正在努力学习它。
我想在 MySQL 数据库中添加记录并且我正在使用事务锁。
我的代码如下。
$SqlQuery="INSERT INTO tab_photo VALUES('$PhotoID','$ProjectId','$Day','$barCode','$photoName','$PhotoXml')";
$waiting = true;
while($waiting) {
try {
// save border data
$stmt = $conn->prepare($SqlQuery);
$conn->beginTransaction();
$stmt->execute();
sleep(1);
$x=$conn->commit();
echo "x value-".$x;
echo "Success";
$waiting = false;
}
catch (PDOException $e){
echo "Failled :".$PhotoID."-".$PhotoID;
if(stripos($e->getMessage(), 'DATABASE IS LOCKED') !== false) {
// This should be specific to SQLite, sleep for 0.25 seconds
// and try again. We do have to commit the open transaction first though
$conn->commit();
usleep(250000);
} else {
$conn->rollBack();
throw $e;
}
}
}
在这里作为它给出的输出,
x value-1 Success
但实际上这条记录并没有添加到数据库中。
我的问题:
- 连commit都成功了(输出1)怎么没有加入到数据库中?
- 如何检查记录是否已添加到数据库中? ( 有没有办法不用写 select 语句就可以找到它?
最佳答案
据我了解,您希望在语句执行失败时抛出 PDOException。但正如我所见,在这种情况下默认情况下不会抛出异常。 查看如何更改 here
假设在你的情况下你应该有这样的代码:
$conn = new PDO($connection_string);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // this will force PDO to throw exception when SQL statement fails instead of simply setting an error.
假设这适合您。
请注意,您不应该使用
$SqlQuery="INSERT INTO tab_photo VALUES('$PhotoID','$ProjectId','$Day','$barCode','$photoName','$PhotoXml')";
取而代之的是,你应该使用参数绑定(bind):
$SqlQuery="INSERT INTO tab_photo VALUES(:PhotoID,:ProjectId,:Day,:barCode,:photoName,:PhotoXml)";
$stmt = $conn->prepare($SqlQuery);
$conn->beginTransaction();
$stmt->execute(array(':PhotoID' => $PhotoID, ':ProjectId' => $ProjectId, ....));
sleep(1);
参见 this了解更多详情。
关于php - 如何使用 commit() 查找记录插入到 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14355830/