mysql autocommit undo_正确使用php mysqli autocommit和rollback

当您拥有一系列必须一起执行的sql语句以保持数据库的一致性时,可以使用它.考虑将提交称为在游戏中建立保存点.无论何时调用回滚,都可以撤消在上一次提交之前完成的所有操作.

想象一下,您需要在发票表中保存发票,invoice_details表中的详细信息以及付款表中的付款.为了保持一致性,您需要确保这些都已完成或者没有完成.如果您在哪里添加发票和详细信息,然后插入付款失败,那么您的数据库将处于不一致状态.

通常这是使用try / catch块完成的,如下所示:

try {

$dbconnect->autocommit(false);

$stmt = $dbconnect->prepare("INSERT INTO `invoices`(`col1`,`col2`) VALUES (?,?)");

$stmt->bind_param('ss',$val1,$val2);

$stmt->execute();

$stmt = $dbconnect->prepare("INSERT INTO `invoice_details`(`col1`,`col2`) VALUES (?,?)");

$stmt->bind_param('ss',$val3,$val4);

$stmt->execute();

$stmt = $dbconnect->prepare("INSERT INTO `payments`(`col1`,`col2`) VALUES (?,?)");

$stmt->bind_param('ss',$val5,$val6);

$stmt->execute();

$dbconnect->commit();

} catch(Exception $e){

// undo everything that was done in the try block in the case of a failure.

$dbconnect->rollback();

// throw another exception to inform the caller that the insert group failed.

throw new StorageException("I couldn't save the invoice");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值