ITeye博客

Perl 数据库事务处理(提交和回滚)

ShellyLi · 2011-12-05 13:24 · perl · 编程语言 · Markdown

use DBI qw(:sql_types);

my $dbh = DBI->connect('dbi:mysql:sample_db','root','password',{

                       PrintError => 0,  
                       RaiseError => 1,  
                       AutoCommit => 0  
                     }  
      ) or die "Connection to sample_db failed: $DBI::errstr";  

my @rows = (
,
,
,
,
);
my $sql = qq{ INSERT INTO teams VALUES ( ?, ?, ? ) };
my $sth = $dbh->prepare( $sql );
foreach $param (@rows) {
eval {
$sth->bind_param( 1, $param->, SQL_VARCHAR );
$sth->bind_param( 2, $param->, SQL_INTEGER );
$sth->bind_param( 3, $param->, SQL_INTEGER);
$sth->execute() or die;
}; if( $@ ) { # If eval failed. $@ is set to the error that occurred
warn "Database error: $DBI::errstr\n";
$dbh->rollback(); # Reverse all commit statements
}else{
$dbh->commit();
}
}
$sth->finish();
$dbh->disconnect();

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。