本文介绍了Perl DBI - 捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

捕获Perl中任何DBI错误的最佳方法是什么?所以例如如果插入失败,因为插入的值中有非法字符,那么我怎么不能让脚本失败,但是捕获错误并正确处理它。



我不想做或死coz我不想停止执行脚本。

解决方案

使用 DBI->连接中的 RaiseError => 1 配置,并将您的呼叫封装到 $ dbh $ sth 在一个try块(和,了解有关其他连接变量的更多信息。



例如:

 使用strict; 
使用警告;

使用DBI;
使用Try :: Tiny;

我的$ dbh = DBI-> connect(
$ your_dsn_here,
$ user,
$ password,
{
PrintError = > 0,
PrintWarn => 1,
RaiseError => 1,
AutoCommit => 1,
}
);
try
{
#在这里查询的故意错字
我的$ data = $ dbh-> selectall_arrayref('SOHW TABLES',{});
}
catch
{
warn得到dbi错误:$ _;
};


Whats the best way of capturing any DBI errors in Perl. So 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" coz 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).

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

这篇关于Perl DBI - 捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 08:32