[英]PHP and MySQL: Running transactions yourself?
The idea of using transactions in MySQL is good. 在MySQL中使用事务的想法很好。 The idea of being able to rollback a transaction if something goes wrong is also good.
如果出现问题,能够回滚事务的想法也很好。
My question is this: In an application, is it worth it to control the transaction myself, or let MySQL take care of it for me? 我的问题是:在一个应用程序中,自己控制事务是值得的,还是让MySQL为我处理它? In other words, should have an active distrust of the autocommit feature that MySQL gives me?
换句话说,应该主动不信任MySQL给我的自动提供功能吗?
Example: 例:
try
{
$mysqli->autocommit( 0 );
//Normally, would go through the steps of prepping and executing etc,
//but I'll use this for brevity.
if( !$mysqli->query( ".." ) )
throw new Exception( ".." );
$mysqli->commit( )
}
catch( Exception $e )
{
$mysqli->rollback( ); //Doing this so I make sure I get my rollback
error_log( ".." );
}
instead of letting the autocommit feature do it's own handy work. 而不是让自动提交功能做它自己的方便工作。
Notes: The application I'm writing is only set up to run one query at a time, there will be no situations (like in some (most) bank and other financial applications) where I'll need to make sure two queries that change data, succeed. 注意:我正在编写的应用程序只设置为一次运行一个查询,没有任何情况(如某些(大多数)银行和其他财务应用程序)我需要确保两个查询更改数据,成功。
This is mainly borne out of a want to control that kind of stuff (and a certain lacktherof in the autocommit feature). 这主要是出于想要控制那种东西(以及自动提交功能中的某些缺点)。
As so often the answer is: it depends. 通常答案是:它取决于。 If you want to ensure that
如果你想确保这一点
update(x);
update(y);
is atomic, ie both updates or none are executed, you should switch off auto-commit. 是原子的,即无论是更新还是不执行,都应该关闭自动提交。 If you are doing just one query, there'll be no need to control transactions yourself.
如果您只进行一次查询,则无需自行控制事务。 If your only transaction fails, there'll be nothing to roll back, right?
如果您的唯一交易失败,那么将无法回滚,对吧?
On a related note: you might want to read about the ACID properties of transactions. 在相关说明中:您可能想要了解事务的ACID属性 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.