到目前為止,我們的動作都還不需要使用到交易機制的功能,不過當下達 UPDATE 或是 DELETE 鈙述時,我們就會希望使用到它了. 根據 DBI 文件指出,如果想製作一套穩固的交易機制,就應該配合 eval{...} 區塊來攔截錯誤的發生,最後再使用 commit 或 rollback 來完成整個交易程序. 這就是我們以下所要談的內容.
本程式示範保證四筆記錄寫入資料庫的方法.
use strict;
use DBI qw(:sql_types);
my $dbh = DBI->connect( 'dbi
BMaker:dbsample',
'jerry',
'jerrypassword',
{
RaiseError => 1,
AutoCommit => 0
}
)
|| die "Database connection not made: $DBI::errstr";
my @records = (
[ 0, "Larry Wall", "
erl Author", "555-0101" ],
[ 1, "Tim Bunce", "DBI Author", "555-0202" ],
[ 2, "Randal Schwartz", "Guy at Large", "555-0303" ],
[ 3, "Doug MacEachern", "Apache Man", "555-0404" ]
);
my $sql = qq{ INSERT INTO employees VALUES ( ?, ?, ?, ? ) };
my $sth = $dbh->prepare( $sql );
for( @records ) {
eval {
$sth->bind_param( 1, @$_->[0]);
$sth->bind_param( 2, @$_->[1]);
$sth->bind_param( 3, @$_->[2]);
$sth->bind_param( 4, @$_->[3]);
$sth->execute();
$dbh->commit();
};
if( $@ ) {
warn "Database error: $DBI::errstr\n";
$dbh->rollback(); #just die if rollback is failing
}
}
$sth->finish();
$dbh->disconnect();