问题
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