本文介绍了设置AutoCommit和begin_work / rollback是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是关于Perl DBI(我在MySQL中使用它)。

This question is about Perl DBI (I use it with MySQL).

我想要以下代码:

{
  local $dbh->{AutoCommit} = 0;
  ...
  if(...) {
    $dbh->rollback;
  }
  ...
}

它将按预期工作吗? (我的意思是回滚后没有多余的提交)$ dbh-> {AutoCommit}是否与$ dbh-> begin_work和$ dbh-> rollback兼容?

Will it work as expected? (I mean no superfluous commit after rollback) Is $dbh->{AutoCommit} compatible with $dbh->begin_work and $dbh->rollback?

推荐答案

是的,您可以这样做,但是为什么要这么做。为什么不直接调用begin_work然后提交或回滚。即使已启用AutoCommit,它们也可以正常工作。

Yes, you can do that but why would you want to. Why not just call begin_work and then commit or rollback. They work fine even if AutoCommit is on.

use strict;
use warnings;
use DBI;
use Data::Dumper;

my $h = DBI->connect();
eval {
    $h->do(q/drop table mje/);
};
$h->do(q/create table mje (a int)/);
my $s = $h->prepare(q/insert into mje values(?)/);

foreach my $it(1..2) {
    {
        local $h->{AutoCommit} = 0;

        $s->execute($it);

        if ($it == 2) {
            $h->rollback;
        } else {
            $h->commit;
        }
    }
}

my $r = $h->selectall_arrayref(q/select * from mje/);
print Dumper($r);

outputs:

$VAR1 = [
          [
            1
          ]
        ];

但以下内容对我来说更好:

but the following looks better to me:

foreach my $it(1..2) {
    $h->begin_work;

    $s->execute($it);

    if ($it == 2) {
        $h->rollback;
    } else {
        $h->commit;
    }
}

这篇关于设置AutoCommit和begin_work / rollback是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 09:42