简体   繁体   English

Perl DBI - 捕获错误

[英]Perl DBI - Capturing errors

What's the best way of capturing any DBI errors in Perl? 在Perl中捕获任何DBI错误的最佳方法是什么? For example if an insert fails because there were illegal characters in the values being inserted, how can I not have the script fail, but capture the error and handle it appropriately. 例如,如果插入失败,因为插入的值中存在非法字符,我怎么能不让脚本失败,而是捕获错误并适当地处理它。

I don't want to do the "or die" because I don't want to stop execution of the script. 我不想做“或死”,因为我不想停止执行脚本。

Use the RaiseError=>1 configuration in DBI->connect , and wrap your calls to the $dbh and $sth in a try block ( TryCatch and Try::Tiny are good implementations for try blocks). DBI->connect使用RaiseError=>1配置,并在try块中包含对$dbh$sth调用( TryCatchTry :: Tiny是try块的良好实现)。

See the docs for more information on other connect variables available. 有关其他可用连接变量的更多信息,请参阅文档

for example: 例如:

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: $_";
};

you can also do the following, which will allow you to die, or gracefully handle the errors and continue. 您还可以执行以下操作,这将允许您死亡或优雅地处理错误并继续。

$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM