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

I've got simple perl script for website
while ( new CGI::Fast ) { my $dbh = DBI->connect( ); # some work with mysql # generating of HTML output }
The question is - Should I disconnect from database at the end of the script? - If this script called very often, is it possible to keep this connection alive, to save time on connections?

Replies are listed 'Best First'.
Re: FastCGI DBI connect/disconnect
by dsheroh (Monsignor) on Nov 12, 2016 at 09:31 UTC
    On your first question, you do not need to explicitly disconnect. When $dbh goes out of scope or the script exits, the connection will automatically be closed.

    On the second, assuming that you are actually running under fcgi (which keeps the script running between requests) rather than traditional CGI (in which the script terminates after handling each request), using connect_cached instead of connect is the easiest way to do it.

    Alternately, if you really wanted to, you could create $dbh outside of your while (CGI::Fast->new) { ... } loop, so that it never goes out of scope, but then you'd need to watch for whether the database connection has timed out and manually reconnect if it has. connect_cached is generally the better option because it handles that for you.

      Alternately, if you really wanted to, you could create $dbh outside of your while (CGI::Fast->new) { ... } loop,

      I would really avoid that in a FastCGI context. A clean disconnect should also either commit or rollback all transactions still open, so every HTTP request sees a clean database connection with no outstanding transactions or other side-effects of a previous request.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
Re: FastCGI DBI connect/disconnect
by Anonymous Monk on Nov 12, 2016 at 02:48 UTC