2011-01-27 108 views
8

在Perl中捕獲任何DBI錯誤的最佳方式是什麼?例如,如果由於插入的值中存在非法字符而導致插入失敗,我如何才能讓腳本失敗,但捕獲錯誤並進行適當處理。Perl DBI - 捕獲錯誤

我不想做「或死」,因爲我不想停止執行腳本。

回答

12

使用RaiseError=>1配置DBI->connect,並在try塊(TryCatchTry::Tiny是try塊很好的實現)包裝您的來電來$dbh$sth

有關其他可用連接變量的更多信息,請參閱the docs

例如:

use strict; 
use warnings; 

use DBI; 
use Try::Tiny; 

my $dbh = DBI->connect(
    $your_dsn_here, 
    $user, 
    $password, 
    { 
     PrintError => 0, 
     PrintWarn => 1, 
     RaiseError => 1, 
     AutoCommit => 1, 
    } 
); 
try 
{ 
    # deliberate typo in query here 
    my $data = $dbh->selectall_arrayref('SOHW TABLES', {}); 
} 
catch 
{ 
    warn "got dbi error: $_"; 
}; 
+1

難道你不應該在`try`塊中放置`connect`嗎? – mscha 2011-01-27 23:13:30

1

你也可以做到以下幾點,這將讓你死,或優雅地處理這些錯誤,然後繼續。

$dbh = DBI->connect($data_src, $user, $pwd) or die $DBI::errstr; 

my $sth = $dbh->prepare("DELETE FROM table WHERE foo = '?'"); 
$sth->execute('bar'); 
if ($sth->err) 
{ 
    die "DBI ERROR! : $sth->err : $sth->errstr \n"; 
}