简体   繁体   English

交易:commit()vs rollBack()

[英]Transaction: commit() vs rollBack()

I have some queries at one script and I want to execute either all of them or none of them ..! 我在一个脚本中有一些查询,我想全部执行或不执行..! I've searched about that and I figured out I have to use transaction . 我搜索了一下,发现必须使用transaction

Actually I want to use PDO::beginTransaction . 实际上我想使用PDO :: beginTransaction Now there is two approaches. 现在有两种方法。

So what's the difference between them? 那么它们之间有什么区别? Both of them seems identical to me, So when should I use which one? 他们两个似乎对我来说都是一样的,那么我什么时候应该使用哪个呢?

<?php

$dbh->beginTransaction();

$sth1 = $dbh->exec("DROP TABLE fruit");
$sth2 = $dbh->exec("UPDATE dessert SET name = 'hamburger'");
$sth3 = $dbh->exec("INSERT INTO names(id, name) VALUES (NULL, 'peter')");

// which one?
$dbh->commit();
// or
$dbh->rollBack();
// ??

/* Database connection is now back in autocommit mode */
?>

您使用提交来执行事务,而回滚则相反,当您想要保持所有内容不变时(例如,如果在事务的某个步骤中检测到某些错误),可以使用回滚。

Both of them seems identical to me 他们俩都和我一样

That's wrong. 错了 Transaction by definition is Atomic in nature means either it will happen and succeed executing all commands in the group or none at all. 根据定义,事务本质上是Atomic ,这意味着它会发生并成功执行组中的所有命令,或者根本不执行。 If it's successful and you want to persist the change then COMMIT else if any of the statement in the group fails then ROLLBACK to get back to pristine state. 如果成功,并且您要保留更改,则执行COMMIT否则如果组中的任何语句失败,则返回ROLLBACK以返回原始状态。

So in your case, you would want to have all the below statement execute successfully and if that then COMMIT to persist the change but if any of the statement fails for any so called reason then it may end up giving a undesired result which you don't want to persist and so ROLLBACK and get back to previous consistent state. 因此,在您的情况下,您将希望成功执行以下所有语句,然后执行COMMIT来保留更改,但是如果任何一条语句由于任何所谓的原因而失败,那么它可能最终会给出不希望的结果,而您不会这样做。想要坚持下去,然后ROLLBACK并返回到先前的一致状态。

$sth1 = $dbh->exec("DROP TABLE fruit");
$sth2 = $dbh->exec("UPDATE dessert SET name = 'hamburger'");
$sth3 = $dbh->exec("INSERT INTO names(id, name) VALUES (NULL, 'peter')");

Read about Transaction and also see this another post PHP + MySQL transactions examples 阅读有关事务的知识 ,也可以参阅另一篇有关PHP + MySQL事务的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM