日期:2014-05-16  浏览次数:20420 次

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->[0], SQL_VARCHAR ); 
        $sth->bind_param( 2, $param->[1], SQL_INTEGER ); 
         $sth->bind_param( 3, $param->[2], 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();