pond2539 发表于 2017-5-19 12:05:44

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

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 = (   
                [ 'A', 3, 5 ],
                [ 'B', 2, 3 ],
               [ 'C', 2, 0 ],
                [ 'D', 6, 0 ],
         );
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();
页: [1]
查看完整版本: Perl 数据库事务处理(提交和回滚)