使用"begin_transaction"的好处是什么? MySQLi中的方法? [英] What is the benefit of using "begin_transaction" method in MySQLi?

查看:104
本文介绍了使用"begin_transaction"的好处是什么? MySQLi中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究MySQLi的回滚管理,并且很好奇begin_transaction()方法的好处是什么.通过关闭自动提交功能,然后执行一些返回成功值的查询,然后根据返回值测试复合布尔值来提交或回滚多条语句,我将看到许多示例完全跳过它.

I'm looking into rollback management with MySQLi, and I'm curious what is the benefit of begin_transaction() method. Many examples I look at skip it entirely by turning autocommit off, then executing some queries with success value returned, and testing a compound Boolean based on the return values to commit or rollback the multiple statements.

在我们希望基于所有查询的成功来提交或回退一组查询的情况下,begin_transaction()方法似乎实际上并没有做任何有用的工作.我可以看到它可能通过显式声明一个事务来增加代码的可读性,但是begin_transaction()除了可读性之外是否还有其他值?它是做什么的?

It doesn't seem like the begin_transaction() method actually does any useful work in a scenario where we are looking to commit or rollback a group of queries based on the success of all of them. I can see that it adds readability to the code perhaps by explicitly declaring a transaction, but is there a value to begin_transaction() other than in readability? What real work does it do?

推荐答案

我总是在PHP中使用mysqli事务而陷入困境,因为涉及该主题的许多示例都涉及到关闭自动提交的方法.虽然可行,但与使用mysqli事务不同.至少从传统意义上讲,通常不会在查询中键入"START TRANSACTION".这是一个在PHP中使用mysqli事务而不弄乱autocommit设置的示例.如果有的话,如果我忘记了如何做的话,这对我自己是一个提醒.

I always get tripped up using mysqli transactions in PHP because many examples that cover this topic throw in the method of turning off autocommit. While that works, it's not the same as using mysqli transactions. At least, not in the traditional sense where one would normally key in 'START TRANSACTION' in the query. Here is an example of using a mysqli transaction in PHP without messing with the autocommit setting. If anything, this is a reminder for myself if I ever forget how to do this.

$dbo->begin_transaction();

//Below are the 2 sample queries we need to run; each one will insert a row into a separate table
$result1 = $dbo->query($query1);
$result2 = $dbo->query($query2);

//If both queries were successful, commit
if ($result1 && $result2)
{
    $dbo->commit();
}
//Else, rollback and throw error
else
{
    $dbo->rollback();
    echo 'Writing to DB failed.';
}

正如其他人提到的那样,它在某种程度上受您的偏好的影响.使用begin_transaction,您无需在查询前后切换自动提交.

As others mention, it is somewhat influenced by your preference. With begin_transaction, you don't have to deal with toggling autocommit before and after your queries.

这篇关于使用"begin_transaction"的好处是什么? MySQLi中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆