简体   繁体   English

在交易中。 每次失败都需要回滚吗? 或不提交就退出脚本就足够了吗?

[英]In a transaction. Do I need to rollback at every fail? or exiting the script without commit is enough?

suppose I have this code 假设我有这段代码

 $transactionfailed = false;
 $mysqliconn->query("begin;");
 //query 1
 $result=$mysqliconn->query("insert into table(col1,col2) values('$val1','val2')");
 if(!$result){$transactionfailed=true;}
 //query 2
 $result=$mysqliconn->query("insert into table2(col1,col2) values('$val1','val2')");
 if(!$result){$transactionfailed=true;}
 if($transactionfailed){$mysqliconn->query("rollback;");}
 else{$mysqliconn->query("commit;");}
 die();

I want to replace it with this one 我想用这个代替它

 $mysqliconn->query("begin;");
 //query 1
 $result=$mysqliconn->query("insert into table(col1,col2) values('$val1','val2')");
 if(!$result){die("error");}
 //query 2
 $result=$mysqliconn->query("insert into table2(col1,col2) values('$val1','val2')");
 if(!$result){die("error");}
 $mysqliconn->query("commit;");
 die();

I want to end the script if something wrong happened without rolling back or committing, depending on mysql database to roll back the transaction if I didn't commit it. 如果不发生任何错误而没有回滚或提交,我想结束脚本,如果我不提交,则取决于mysql数据库回滚事务。

I tried it many times, and yes it do rollback the transaction if I exit without commit. 我尝试了很多次,是的,如果我退出而不提交,它会回滚事务。 but is this always SAFE ? 但这总是安全吗? . or there is something I miss. 还是我想念的东西 because I don't want that query2 is failed and query1 is committed one day later. 因为我不希望query2失败并在一天后提交query1。

I suggest using try/catch blocks, 我建议使用try / catch块,
put 'begin' query before try block 将“开始”查询放在try块之前
put your 'insert' queries in the try block 将您的“插入”查询放入try块
put your 'rollback' query in the catch block 将您的“回滚”查询放入catch块
if no query failed in the try block 'commit' once lastly in the try block 如果没有在try块“提交”中失败的查询,最后一次在try块中
if any query failed in the try block 'rollback' once in the catch block (all queries after the begin query will be rolled back) 如果在catch块中一次try块“ rollback”中的任何查询失败(begin查询之后的所有查询将被回滚)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM