DBD :: mysql :: st fetchrow_array失败:fetch()没有execute()

时间:2011-09-29 14:25:54

标签: perl

fetchrow_hashref工作正常,但是当我使用fetchrow_array获取以下错误时。

#!/usr/bin/perl

use warnings;
use DBI;

$DB_name    = 'database';
$DB_user    = 'root';
$DB_pwd     = '';
my $dsn = 'dbi:mysql:avm:localhost:3306';

$dbh = DBI->connect($dsn,"$DB_user","$DB_pwd");

print "\nConnection error: $DBI::errstr\n\n";

$sth  = $dbh->prepare("SELECT * FROM tblmanufacturer");
$sth->execute();

while ( ($id,$name) = $sth->fetchrow_array() ) 
{
        print "$id\t\t $name \n";
}

$sth->finish();

$dbh->disconnect();
  

DBD :: mysql :: st fetchrow_array失败:fetch()没有执行()

4 个答案:

答案 0 :(得分:4)

我总是在“执行”和“准备”错误时使用“die”。

$sql = $dbh->prepare( $query ) or die "Unable to prepare $query" . $dbh->errstr;
$sql->execute() or die "Unable to execute '$query'.  " . $sql->errstr;

答案 1 :(得分:3)

检查execute()和/或print "$DBI::errstr\n\n"的返回值,看看执行是否失败。

print $sth->execute(),"\n";

答案 2 :(得分:2)

另一种方法是使用错误处理程序捕获错误,执行您需要的任何操作(将其发送到您的日志文件,打印它们,死掉或继续执行脚本)。
这消除了在每种方法之后" or die() "的需要。可以找到有关HandleError方法的文档here

对于初学者来说这个简单的例子:

#!/usr/bin/perl

use strict;
use warnings;
use DBI;

my $DB_name    = 'database';
my $DB_user    = 'root';
my $DB_pwd     = '';
my $dsn = 'dbi:mysql:avm:localhost:3306';
my ($sth, $id, $name);

my $dbh = DBI->connect($dsn,$DB_user,$DB_pwd, { PrintError => 0, ShowErrorStatement => 1, HandleError => \&dbi_error_handler,} );

$sth  = $dbh->prepare("SELECT * FROM tblmanufacturer");
$sth->execute();

while ( ($id,$name) = $sth->fetchrow_array() ) 
{
        print "$id\t\t $name \n";
}

$sth->finish();
$dbh->disconnect();

sub dbi_error_handler
{
    my( $message, $handle, $first_value ) = @_;
    # print to your log file, call your own logger etc ... 
    # here it will die() to be similar to "or die()" method, but the line number is incorect
    die($message);
    # if you return false it will check/execute RaiseError and PrintError
    return 1;
}

P.S。没有理由将字符串变量封装在引号中:($dsn,"$DB_user","$DB_pwd");,不要这样做,有关详细信息,请阅读this

答案 3 :(得分:1)

由于在我完成之前重用了 $sth,我在 apache fcgid 中遇到了这个错误。我只在 apache 错误日志中看到它。在准备和执行语句之后放入“or die ...”没有任何帮助,并且脚本无论如何似乎都可以正常工作(在正常使用中只有一行提取,但有可能更多)就像它所做的那样遇到错误之前的预期。 错误刚刚出现在 Apache 日志中。 简单的修复,将 $sth 重命名为 $osth,问题就消失了。 如果您看到此错误并重新使用语句句柄,请尝试使用唯一的语句句柄以查看问题是否消失。

# rename to $ostmt
my $stmt="SELECT ...";
# rename to $osth
my $sth=$dbh->prepare($stmt) or die "Unable to prepare $stmt" . $dbh->errstr;
$sth->execute() or die "Unable to execute '$stmt'.  " . $sth->errstr;
while( my ( $f1, $f2 ... ) = $sth->fetchrow_array() ){
  # redeclare $stmt and $sth below using my $stmt, my $sth
  $stmt="SELECT ...";
  $sth=$dbh->prepare($stmt) or die "Unable to prepare $stmt" . $dbh->errstr;
  $sth->execute($f1) or die "Unable to execute '$stmt'.  " . $sth->errstr;
  my ( @stuff ) = $sth->fetchrow_array();
  # ...
  # do lots of stuff
  # ...
  # output fcgi content
} # error kicks in here

它比上面的示例要复杂得多,但错误非常无用,所以我留下这个答案,以防它对其他人有帮助。