Just to clarify that calling finish() means you are merely finished with the current query and its results and you can now safely call execute() again. No need to call prepare() again first.
I got caught by this one on AIX using the ODBC driver to a DB2 SQL database. I think it was AIX that had an old ODBC driver perhaps because things were fine on Linux.
Anyway, I did an SQL query that returns one row, over and over in a for loop as follows and got the 24000 error.
my $sth = $dbh->prepare( $query ) or die "dying";
foreach my $i (@blah)
{
$sth->execute($fred, $i) or die "dying";
my $hash_ref = $sth->fetchrow_hashref("NAME_uc"); # only a single row exists
...
$sth->finish(); # MUST do this
}
My conclusion is that I had to call $sth->finish() so that I could safely call $sth->execute() again, otherwise I could get "Invalid cursor state. SQLSTATE=24000" error message.
This is because we must make sure we completely read or fetch all the data set before moving to the next statement.$sth->finish() indicates to DBI that you are finished with the
statement handle. It can then be reused for a call to execute()
I also found that I could instead put the fetch in a while loop, even though only one row is ever returned but the query. It seems trying to fetch the next non-existent row also makes the sth resuable for an execute.
my $sth = $dbh->prepare( $query ) or die "dying";
for
{
$sth->execute($fred, $i) or die "dying";
while (my $hash_ref = $sth->fetchrow_hashref("NAME_uc"))
{
...
}
}
Both solutions worked for me. :)