[英]perl dbi rollback not working
i am using this approach. 我正在使用这种方法。 If there is an error in the sql, rollback only happens for the first id of the asset_group.
如果sql中有错误,则仅对asset_group的第一个ID进行回滚。 Rest of the ids are ignored.
其余的ID将被忽略。 Am i doing it the right way?
我做对了吗?
my $sql = "sql batch that update and insert depending on the condition";
$dbh->{RaiseError} = 1;
$dbh->{PrintError} = 0;
$dbh->{AutoCommit} = 0;
my $sth = $dbh->prepare($sql);
my @error = ();
my $num = 0;
foreach my $id (@asset_group) {
next if ($id eq '');
eval {
$sth->bind_param(1, $id);
$sth->bind_param(2, $vars{'other_id'});
$sth->execute();
};
if ($@) {
$dbh->rollback();
push @error, $@
} else {
$dbh->commit();
}
}
Depending on the database, you may need to issue a begin work before you start changing things. 根据数据库的不同,您可能需要在开始更改之前发出开始工作 。 I seem to remember Informix requiring one.
我似乎记得Informix需要一个。
Also, it looks like you are issuing a commit or a rollback after each execute. 同样,您似乎在每次执行后都发出提交或回滚。 Once you commit, you can't rollback.
一旦提交,就无法回滚。 Normally one says something like
通常有人说
$dbh->begin_work;
eval {
for my $id (@asset_group) {
next if ($id eq '');
$sth->execute($id, $vars{other_id});
}
1; #if it doesn't die then this will force it to return true
} or do {
my $error = DBI->errstr;
$dbh->rollback();
die "could not insert rows: $error\n"
};
$dbh->commit();
Note how I don't use $@
. 注意我如何不使用
$@
。 $@
is untrustworthy . $@
是不可信的 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.