如何在Perl中捕获任何DBI错误?例如,如果插入失败,因为要插入的值中存在非法字符,我该如何避免脚本失败,而是捕获错误并适当处理它。
我不想使用"or die",因为我不想停止脚本的执行。
如何在Perl中捕获任何DBI错误?例如,如果插入失败,因为要插入的值中存在非法字符,我该如何避免脚本失败,而是捕获错误并适当处理它。
我不想使用"or die",因为我不想停止脚本的执行。
在DBI->connect
中使用配置RaiseError=>1
,并在调用$dbh
和$sth
时将其包装在try块中(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";
}
connect
放在try
块中吗? - mscha