matth has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I get this error:
DBD::mysql::st fetchrow_array failed: fetch() without execute() at que +ry_B_testing_changes.pl line 35.
For this bit of my Perl code:
$dbh=DBI->connect('DBI:mysql:genome', 'u', 'p'); $sth = $dbh->prepare ("SELECT P.gene_name_M FROM para_n P WHERE P.number_genes_group = 4"); $sth->execute () while (@ary = $sth->fetchrow_array ()) { foreach (@ary) { #...........rest of code
Can any monks kindly explain why?

Replies are listed 'Best First'.
Re: Perl DBI problem
by diotalevi (Canon) on Jun 13, 2003 at 23:02 UTC

    You forgot the semi-colon after the $sth->execute() and it is being interpreted as used for the while(). Probably.

Re: Perl DBI problem
by barrd (Canon) on Jun 14, 2003 at 12:31 UTC
    Hi matth,

    In addition to diotalevi's reply above I'd add the following. If you had used '$DBI::errstr' that would have given you more insight into what was going wrong. Below is a little self contained programme that includes using strict and warnings, which is generally considered "good practice" round here.

    #!/usr/bin/perl -w use strict; use DBI; my $dbh = DBI->connect('DBI:mysql:genome', 'u', 'p') || die $DBI::er +rstr; my $sth = $dbh->prepare("SELECT foo FROM bar WHERE baz = 4"); $sth->execute() || die $DBI::errstr; while (my ($foo) = $sth->fetchrow()) { # Do something with $foo eg: print "foo = $foo\n"; } $sth->finish(); $dbh->disconnect() || warn $DBI::errstr;

    Give that a try and see what happens, hope it helps.
    barrd

      But why use $DBI::errstr in such a simple situation when you can turn the RaiseError attribute on instead? :)
      my $dbh = DBI->connect( qw(DBI:vendor:database:host user pass), {RaiseError => 1}, ); my $sth = $dbh->prepare('get me some records and stuff'); $sth->execute;

      jeffa

      L-LL-L--L-LL-L--L-LL-L--
      -R--R-RR-R--R-RR-R--R-RR
      B--B--B--B--B--B--B--B--
      H---H---H---H---H---H---
      (the triplet paradiddle with high-hat)
      
        Hi jeffa,

        Fair enough, I don't use that method as I prefer what might be known as the long hand approach. You are probably correct. I haven't tried RaiseError so if you or anyone else could answer the following I'd be grateful (and may even change my mind as to how to go about doing error exceptions ;).

        My understanding is this: $DBI::errstr method returns the native database engine error message from the last driver function called. Does using RaiseError do exactly the same thing? And AFAIR RaiseError is used to "force errors" - will it implicitly 'die' on any error?

        I'm just another monk trying to learn from my peers and betters.
        barrd

Re: Perl DBI problem
by Itatsumaki (Friar) on Jun 14, 2003 at 15:00 UTC

    Just this past week gmax posted an excellent node on solving and debugging database related issues like this one. It's definitely worth a read.

    -Tats