gpt4 book ai didi

php - 事务内的Mysql事务

转载 作者:IT老高 更新时间:2023-10-28 12:56:24 25 4
gpt4 key购买 nike

在一个使用 mysql 数据库的 PHP 脚本中,我最近需要在恰好位于另一个事务中的某个点使用一个事务。我所有的测试似乎都表明这很好,但我找不到任何关于这种用法的文档。

我想确定——事务中的事务在 mysql 中是否有效?如果是这样,有没有办法找出嵌套事务的深度有多少? (即恢复正常需要多少回滚)

提前致谢,布赖恩

最佳答案

与其他人的答案相反,您可以在交易中有效地创建交易,这真的很容易。您只需创建 SAVEPOINT 位置并使用 ROLLBACK TO savepoint 来回滚部分事务,其中 savepoint 是您为保存点指定的任何名称。MySQL 文档链接:http://dev.mysql.com/doc/refman/5.0/en/savepoint.html当然,事务中任何地方的查询都不应该是隐式提交的类型,否则将提交整个事务。

例子:

START TRANSACTION;

# queries that don't implicitly commit

SAVEPOINT savepoint1;

# queries that don't implicitly commit

# now you can either ROLLBACK TO savepoint1, or just ROLLBACK to reverse the entire transaction.

SAVEPOINT savepoint2;

# queries that don't implicitly commit

# now you can ROLLBACK TO savepoint1 OR savepoint2, or ROLLBACK all the way.
# e.g.

ROLLBACK TO savepoint1;
COMMIT; # results in committing only the part of the transaction up to savepoint1

我在 PHP 中写过这样的代码,而且效果很好:

foreach($some_data as $key => $sub_array) {
$result = mysql_query('START TRANSACTION'); // note mysql_query is deprecated in favor of PDO
$rollback_all = false; // set to true to undo whole transaction
for($i=0;$i<sizeof($sub_array);$i++) {
if($sub_array['set_save'] === true) {
$savepoint = 'savepoint' . $i;
$result = mysql_query("SAVEPOINT $savepoint");
}
$sql = 'UPDATE `my_table` SET `x` = `y` WHERE `z` < `n`'; // some query/queries
$result = mysql_query($sql); // run the update query/queries

$more_sql = 'SELECT `x` FROM `my_table`'; // get data for checking
$result = mysql_query($more_sql);

$rollback_to_save = false; // set to true to undo to last savepoint
while($row = mysql_fetch_array($result)) {
// run some checks on the data
if( /*some check says to go back to savepoint */) {
$rollback_to_save = true; // or just do the rollback here.
}
if( /* some check says to rollback entire transaction */ ) {
$rollback_all = true;
}
}
if($rollback_all === true) {
mysql_query('ROLLBACK'); // rollback entire transaction
break; // break out of for loop, into next foreach
}
if($rollback_to_save = true) {
mysql_query("ROLLBACK TO $savepoint"); // undo just this part of for loop
}
} // end of for loop
mysql_query('COMMIT'); // if you don't do this, the whole transaction will rollback
}

关于php - 事务内的Mysql事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1490846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com