Setting AutoCommit and begin_work/rollback are the same?

此生再无相见时 提交于 2020-01-15 05:36:45

问题


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

I want the following code:

{
  local $dbh->{AutoCommit} = 0;
  ...
  if(...) {
    $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?


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/12881182/setting-autocommit-and-begin-work-rollback-are-the-same

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!