如何使用 commit() 查找记录插入到 mysql [英] how to find record insert to mysql using commit()
问题描述
抱歉这个初学者的问题,我不是 PHP 开发人员,但现在我正在努力学习.
Sorry for this beginners question and i'm not a PHP developer, but now i'm trying to learn it.
我想在 MySQL 数据库中添加记录,我正在使用事务锁.
i want to add record in MySQL data base and i'm using transactions lock.
我的代码如下.
$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;
}
}
}
在这里作为它给出的输出,
in here as output it gives,
x value-1 Success
但实际上这条记录并没有添加到数据库中.
but actually this record doesn't add to the database.
我的问题:
- 即使提交成功(输出 1)它怎么不添加到数据库中?
- 如何检查记录是否添加到数据库中?(有没有什么办法不用写select语句就可以找到它?
推荐答案
据我所知,您希望在语句执行失败时会抛出 PDOException.但正如我所见,在这种情况下,默认情况下不会抛出异常.在此处
As I understand, you expect that PDOException will be thrown when statement is failed to execute. But as I can see, exception is not thrown by default in such cases. See how you can change that here
假设在你的情况下你应该有一个这样的代码:
Suppose in your case you should have a code like this:
$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')";
相反,您应该使用参数绑定:
Instead of that, you should use parameters binding:
$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);
有关详细信息,请参阅此.
See this for more details.
这篇关于如何使用 commit() 查找记录插入到 mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!