MySQLi事务回滚失效:InnoDB表Commit后Rollback不生效
事务回滚失效问题排查与解决
问题描述
配置事务回滚时,INSERT操作始终无法回滚,已确认目标表引擎为InnoDB:
Name Engine Version Row_format order_fulfillment_discounts InnoDB 10 Dynamic
简化后的测试代码如下:
$dbConnect = mysqli_connect("localhost", "root", "", "dealers"); $dbConnect->autocommit(false); $dbConnect->begin_transaction(); $dbConnect->query("INSERT INTO order_fulfillment_discounts (fulfillment_id, order_id, discount_id, discount_type, discount_category) VALUES (1,1,1,'foo','test')"); $dbConnect->commit(); $dbConnect->rollback();
- 代码无其他依赖或额外数据库连接,
commit()执行后INSERT操作生效,说明事务基础功能可用 commit()和rollback()返回结果均为TRUE- 运行环境为Mac + Homebrew PHP 8,root账户拥有全数据库权限,尝试过设置数据库密码、在
commit()与rollback()间添加延迟、指定事务名称等操作,回滚始终无效
问题根源与解决方案
核心问题是你先执行了commit()提交事务,之后调用rollback()完全无效。事务提交后,所有操作已持久化到数据库,此时没有任何可撤销的未提交内容。
正确的事务逻辑示例
应该在确认操作无误后提交,操作失败或需要撤销时回滚:
$dbConnect = mysqli_connect("localhost", "root", "", "dealers"); $dbConnect->autocommit(false); $dbConnect->begin_transaction(); // 执行插入操作 $result = $dbConnect->query("INSERT INTO order_fulfillment_discounts (fulfillment_id, order_id, discount_id, discount_type, discount_category) VALUES (1,1,1,'foo','test')"); if ($result) { // 操作成功,提交事务 $dbConnect->commit(); } else { // 操作失败,回滚事务 $dbConnect->rollback(); }
测试回滚功能的代码
如果只是验证回滚效果,直接调用rollback()即可,不要提前提交:
$dbConnect = mysqli_connect("localhost", "root", "", "dealers"); $dbConnect->autocommit(false); $dbConnect->begin_transaction(); $dbConnect->query("INSERT INTO order_fulfillment_discounts (fulfillment_id, order_id, discount_id, discount_type, discount_category) VALUES (1,1,1,'foo','test')"); // 直接回滚,不提交事务 $dbConnect->rollback();
内容的提问来源于stack exchange,提问作者Notsileous
相关产品推荐
相关产品推荐

