DBD :: mysql :: st fetchrow_array failed: fetch () without execute ()

fetchrow_hashref working fine, but when I use fetchrow_array I get the following error.

 #!/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 failed: fetch () without execute () in

+7
source share
3 answers

Check the return value of execute() and / or print "$DBI::errstr\n\n" and check if execution is running.

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

I always use "dying" from errors in the "execution" and "preparation".

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

Another way is to fix the errors with the error handler, do whatever you need (send it to the log file, print, die or continue the script).
This eliminates the need for " or die() " after each method. The documentation for the HandleError method can be found here .

To get started, take this simple example:

 #!/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; } 

PS There is no reason to encapsulate yout string variables in quotation marks here: ($dsn,"$DB_user","$DB_pwd"); do not do this, for more information on this, read this .

+2
source

All Articles