http://www.perlmonks.org?node_id=275638


in reply to Persistent DBI connection with mySQL

As mentioned already, Apache::DBI.

There is also connect_cached() via the standard DBI.

This allows you to select which connections that you want to be persistant (connect_cached)and which you don't (connect).

The DBI keeps a hash of the connection options and reuses the open connection if the options are identical.

I use this on my mod_perl sites, so that if I access a database very rarely, or with unusual options, I can single it out not to persist and yet get all the benefits of the ones that are used frequently, persisting. One example of this is a report which takes a while to run anyway since it's big and thus the connection overhead is not noticable and is only run every once in a while. If I kept the connection around and the child process lasted long enough for another call to the report, the likelihood that the same child would get the request a week from now is remote at best, so a new connection would be made anyway. Thus I go ahead and toss the connection as soon as the page is sent to the user.

There is also prepare_cached but this reqiures some forethought as you are reusung a statement handle and you need to be aware of the effect of context of calling these from different subs for example. This is handy where the query plan takes a while to generate and you need to do the same query frequently.