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

Hello Monks,

I have a question about prepare_cached() statements. The relevant extract from my script runs like this:

sub get_account_status { my ($account_num) = shift; my $query = qq { SELECT a.STATUS FROM account a WHERE a.ACCOUNT_NUMBER = ? }; my $sth = $dbh->prepare_cached($query); $sth->execute($account_num); my $status = $sth->fetchrow_array; return uc($status); }

And when I run this I get this warning: "statement handle still active at <line number of the prepare_cached statement>".

After fetching the result, if I say,

$sth->finish;

then the warning vanishes. So I thought that there might be multiple status values for each account number and I might not be fetching all of them. But given the fact that account number is the primary key on this table, this seemed impossible. Also, if I query the table directly, I get only one status value for each account number.

I believe, I am not properly using prepare_cached (and yes, this is the first time I am using it!!).

Any suggestions??

Thanks,

Replies are listed 'Best First'.
Re: prepare_cached warning
by runrig (Abbot) on Jun 15, 2007 at 18:39 UTC
    Unless you fetch to the end of the results (when $sth->fetchrow* returns false), the statement handle is active. So you can either call $sth->finish(), or call one of the selectrow_* methods (you can still use prepare_cached, just pass selectrow_* the statement handle instead of a sql statement).
      runrig,

      Thank You. selectrow works well. Also, does calling $sth->finish, affect the "caching" of the prepared statement?

        does calling $sth->finish, affect the "caching" of the prepared statement?

        No. But if you use selectrow_, there is no need to call finish().

Re: prepare_cached warning
by pajout (Curate) on Jun 16, 2007 at 16:38 UTC
    Alternatively, you can use selectall_arrayref or fetchall_arrayref methods if you expect more than one row in query result. Sometimes it is better to obtain all rows of query result in one command, sometimes it is better to fetch in loop, but maximally 100 rows in one command.
    Anyway, DBI documentation will show you possibilities how to write your applications.