我试图将运行时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
。显示唯一的一个。
答案 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});