如果 PHP PDO 事务失败,我必须显式 rollback() 吗?
我看过一个代码示例,其中有人
$dbh->rollback();
在发生 PDOException 时执行 a 操作。我以为数据库会在这种情况下自动回滚?
I've seen an code example where someone does a
$dbh->rollback();
when there occurs an PDOException. I thought the database will rollback automatically in such a case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您不
提交
也不回滚
打开的事务,并且它在脚本中的任何地方都没有提交
,那么它就不会已提交
(如数据库引擎所见),并将在脚本结束时自动回滚。尽管如此,我(嗯,几乎)总是显式地
提交
或回滚
我打开的事务,所以:$db->rollback()
时,他知道我想要事务肯定会回滚,并且他不必思考“他真的想回滚吗?还是他忘记了什么?以及脚本后面的内容呢?”数据库引擎不会“看到” PDOException :它是由 PHP 在各种条件下抛出的 - 但数据库本身不会回滚任何内容:
If you don't
commit
notrollback
an opened transaction, and it's notcommited
anywhere later in your script, it won't becommited
(as seen by the database engine), and will automatically rolled-back at the end of your script.Still, I (well, almost) always
commit
orrollback
explicitly the transactions I open, so :$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 ?"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 :