码迷,mamicode.com
首页 > 其他好文 > 详细

PDO如何完成事务操作

时间:2019-09-12 18:12:07      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:nsa   回滚   pen   操作   overflow   isp   ike   html   导致   

起因

无意间翻看极客学院的APP,准备找一些教程看看.看到一篇PDO 安全处理与事务处理,一想对MySQL的事务处理仅仅停留在概念上(知道执行多条语句,其中一个失败了,就会回滚操作)。但是把概念变成代码还真没实践过,于是就打开了。

视频讲解的还是比较基础详细的:

MySQL数据表应该为InnoDB类型

事务处理操作方法主要包括:

  1. beginTransaction() //开启一个事务

  2. commit() //事务提交

  3. rollBack() //事务回滚操作

PS:

PDO::ATTR_ERRMODE:错误报告

PDO::ERRMODE_SILENT: 仅设置错误代码

PDO::ERRMODE_WARNING: 引发 E_WARNING 错误

PDO::ERRMODE_EXCEPTION: 抛出 exceptions 异常

但是其中一段代码是有问题的,首先我看到的是roolback拼错了,然后仔细一看:先die掉,然后执行rollBack方法,肯定是有问题的啊。

但是实际执行过程中,因为对name字段有个唯一索引,事务并没有成功提交。而且rollBack方法也没有执行。但是数据却没有插入。本来想着一上午就搞定的问题,因为这个问题的出现,导致又花费几个小时解决。

问题

问题:Is it necessary to rollback if commit fails?

$mysqli->autocommit(false); //Start the transaction
$success = true;    

/* do a bunch of inserts here, which will be rolled back and
   set $success to false if they fail */

if ($success) {
    if ($mysqli->commit()) {
        /* display success message, possibly redirect to another page */
    }
    else {
        /* display error message */
        $mysqli->rollback(); //<----------- Do I need this?
    }
}

$mysqli->autocommit(true); //Turns autocommit back on (will be turned off again if needed)

//Keep running regardless, possibly executing more inserts

SF上也有相同的疑问~~~ 并且没人能解答。

解决

紧接着又找,看来也有人跟我相同的疑问,rollBack方法会自动执行?终于找到了答案!

If you don‘t commit not rollback an opened transaction, and it‘s not commited anywhere later in your script, it won‘t be commited (as seen by the database engine), and will automatically rolled-back at the end of your script.

上述引用大概的意思是:在开启一个事物没有执行commit方法或者rollBack方法,在脚本最后也不会执行commit方法并且在脚本最后将会执行rollBack方法。

参考中还提到方便别人理解,否则别人不知道是否需要回滚操作,还是之后写了。

The code is more easy to read / understand : when one sees $db->rollback(), he knows I want the transaction rolled-back for sure, and he doesn‘t have to think "did he really want to rollback, or did he forget something ? and what about later in the script ?"

注意

因此,设想唯一索引字段插入了一条相同的数据,导致程序进入捕捉了异常。此时没有写rollback执行回滚操作。而项目组其他人员不知道最终执行执行过rollback操作。大A写了一个rollback方法,经过大量代码,小d又写了一个rollback操作,从而又抛出可一个新的异常:"There is no active transaction",没开始一个激活的事务。

参考

http://www.jikexueyuan.com/course/653.html
http://stackoverflow.com/questions/38133260/is-it-necessary-to-rollback-if-commit-fails
http://stackoverflow.com/questions/2001698/if-an-php-pdo-transaction-fails-must-i-rollback-explicitely

PDO如何完成事务操作

标签:nsa   回滚   pen   操作   overflow   isp   ike   html   导致   

原文地址:https://www.cnblogs.com/luyuqiang/p/pdo-transaction.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!