[英]Perl DBI - Capturing errors
在Perl中捕獲任何DBI錯誤的最佳方法是什么? 例如,如果插入失敗,因為插入的值中存在非法字符,我怎么能不讓腳本失敗,而是捕獲錯誤並適當地處理它。
我不想做“或死”,因為我不想停止執行腳本。
在DBI->connect
使用RaiseError=>1
配置,並在try塊中包含對$dbh
和$sth
調用( TryCatch和Try :: Tiny是try塊的良好實現)。
有關其他可用連接變量的更多信息,請參閱文檔 。
例如:
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: $_";
};
您還可以執行以下操作,這將允許您死亡或優雅地處理錯誤並繼續。
$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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.