---
title: "Perl 数据库事务处理（提交和回滚）"
author: "ShellyLi"
date: "2011-12-05T13:24:01Z"
tags: []
categories: ["编程语言"]
slug: "perl"
draft: false
lastmod: "2011-12-05T13:27:04Z"
id: 1292047
url: "https://shellyli.iteye.com/blog/1292047"
---

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();