如何在变量中存储运行时mssql错误并继续在perl中运行?

时间:2017-01-02 08:46:21

标签: sql-server perl dbi

我试图将运行时mssql错误存储在变量中并继续使用所有其他数据。

my $sth = $dbh->prepare("exec TEST_ABC_DB.dbo.testprocedure");
$sth->execute() ;
my $db_error =$DBI::errstr; #It didn't work also I tried err and state
print "\nDB error $db_error\n";
while (@row = $sth->fetchrow_array( ) ) 
{
      print "Row: @row\n";
}

我使用了eval块,但它也无效。

我的程序如下,(样本)

CREATE procedure  testprocedure as
select 'one'
select 'three'
select 10/0
select 'five'

当我运行脚本时,它会显示

输出

Row: one
DBD::ODBC::st finish failed: [unixODBC][FreeTDS][SQL Server]Divide by zero error encountered. (SQL-22012) at testing.pl line 24.
DBI::db=HASH(0xbe79a0)->disconnect invalidates 1 active statement handle (either destroy statement handles or call finish on them before disconnecting) at testing.pl line 28.

甚至不显示输出three。显示唯一的一个。

2 个答案:

答案 0 :(得分:2)

  

PrintError句柄属性告诉DBI调用Perl warn()   功能(通常会导致错误被打印到   遇到屏幕时)和RaiseError句柄属性(哪个   告诉DBI通常在出错时调用Perl die()函数   导致脚本立即中止)。 - Programming the Perl DBI

因此,您可以使用以下方法来处理这种情况。

local $SIG{__DIE__} = sub {
    my ($die_message) = @_;
    #do something..
};
  

我试图将错误存储在变量

在上面的代码段$die_message中将包含错误消息。

另一种选择是将RaiseError设置为0,将PrintError设置为1,以便获得warn但程序不会die。< / p>

  

<强> PrintError

     

PrintError属性可用于强制生成错误   警告(使用警告)以及返回错误代码   正常的方式。当设置&#34; on&#34;时,任何导致错误的方法   发生将导致DBI有效地执行warn("$class $method failed: $DBI::errstr"),其中$class是驱动程序类   $method是失败的方法的名称。

     

<强> RAISEERROR

     

RaiseError属性可用于强制引发错误   异常而不是简单地以正常方式返回错误代码。它   是&#34;关&#34;默认情况下。当设置&#34; on&#34;时,任何导致a的方法   错误将导致DBI有效地执行die("$class $method failed: $DBI::errstr"),其中$class是驱动程序类   $method是失败的方法的名称。

来源 - DBI docs

你也可以通过

手动完成
my $dbh=DBI->connect(....{RaiseError=>1}) or die...
my $sth=$dbh->prepare(...);
{
   local $dbh->{RaiseError} = 0;
   $sth->execute;
   if ($sth->Errstr) {
       # handle the error
   }
}
# $dbh->{RaiseError} is back to normal here

答案 1 :(得分:0)

我从this回答中得到了我的问题的答案。

最终答案是

do
{ 
while(my @row=$sth->fetchrow_array())
{
    if ($sth->errstr) 
    {
        my $Error = $sth->errstr;   

    }
    print $row[0]."\n\n";
}
} while ($sth->{odbc_more_results});