dbi statement handlers as package globals in mod_perl script

A

Andrew S

I am working to enhance the performance of a few mod_perl scripts on
some clients' web sites. One of the optimizations that I have read
about is to store DBI statement handles as package globals, so that
they can be re-used within the same process. My concern is that
something bad may happen if/when a database connection is dropped. I
realize that Apache::DBI will handle dropped connections gracefully,
but all statement handles prepared from the original database handle
will become invalid, won't they?

Here is some code:

========
use Apache::DBI;
use strict;
use vars($dbh $sth);
....
$dbh ||= DBI->connect(...);
$sth ||= $dbh->prepare("select * from tbl where id = ?");
....
$sth->execute($id);
@result = $sth->fetchrow_array;
....
========

The idea here is to initialize a database handle and a statement handle
once when the script is first loaded by a process. Thereafter, any web
requests handled by the same process can re-use the statement handle.
To the best of my knowledge, this is the most optimal solution. If I
initialized the statement handle every time the code was run, then I
would incur the overhead of calling the prepare method every time. But
as I said, I am a little paranoid about what would happen to $sth if
the database connection associated with $dbh has to be re-established.

Has anyone ever used package-global statement handles successfully? If
so, can you tell me whether the above code is right. Otherwise, what
recommendations would you make?
 
B

Brian McCauley

Andrew said:
I am working to enhance the performance of a few mod_perl scripts on
some clients' web sites. One of the optimizations that I have read
about is to store DBI statement handles as package globals, so that
they can be re-used within the same process. My concern is that
something bad may happen if/when a database connection is dropped. I
realize that Apache::DBI will handle dropped connections gracefully,
but all statement handles prepared from the original database handle
will become invalid, won't they?

Just use prepare_cache() and let someone else worry about that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top