如果PHP PDO事务失败,我是否必须明确地rollback()? [英] If an PHP PDO transaction fails, must I rollback() explicitely?
问题描述
我看过一个代码示例,其中有人进行了
I've seen an code example where someone does a
$dbh->rollback();
当发生PDOException时.我以为这种情况下数据库会自动回滚?
when there occurs an PDOException. I thought the database will rollback automatically in such a case?
推荐答案
如果您不是commit
不是rollback
一个已打开的事务,并且在脚本的后面任何地方都不是commited
,则不会commited
(如数据库引擎所见),并将在脚本末尾自动回滚.
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
明确地打开我打开的交易,所以:
Still, I (well, almost) always commit
or rollback
explicitly the transactions I open, so :
- 没有错误的风险(例如稍后在脚本中错误地"提交)
- 代码更易于阅读/理解:当看到
$db->rollback()
时,他知道我肯定希望事务回滚,而他不必思考"他是否真的想回滚,还是他忘记了什么?脚本的后续内容又如何?"
- There is not risk of an error (like commiting "by mistake" later in the script)
- 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 ?"
数据库引擎没有看到" PDOException:PHP在各种情况下都会抛出它-但是数据库本身不会回滚任何东西:
The DB engine doesn't "see" the PDOException : it is thrown by PHP under various conditions -- but the database doesn't rollback anything by itself :
- 交易已提交
- 或已回滚
- 或者它没有被明确提交或回滚-这意味着它未被提交-这意味着被修改的内容没有被真正"修改
这篇关于如果PHP PDO事务失败,我是否必须明确地rollback()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!