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

Dear Monks,

I've this program that once in a while runs for weeks. But, after running for a few days, somehow the connection with the database gets lost. I searched the form and found mysql_auto_reconnect, which seems to work. I've tested it by doing
$mysql->disconnect() ; $sth = $mysql->prepare(...) ; ......
So, how can I tell now if I'm disconnected ?
But, I don't really like this solution, because this only works if you have $mysql->{autocommit} = 1
So what I tried was:
$sth = $mysql->prepare(...) ; if ( ! $sth-execute() ) { # connection lost ? # reconnect }
So I assumed that if a request failed, the connection was lost. Anyway, to simulate a lost connection I added before the prepare() a
But now, my perl script stops when it tries to execute the sql command ?

Any suggestions ?

Thanks a lot in advance

Replies are listed 'Best First'.
Re: mysql_auto_reconnect
by idle (Friar) on Jan 27, 2006 at 12:38 UTC
    You can check your connection with attribute {Active}.
    my $h=$dbh->{Active}; &reconnect if (!$h);
      This is not for checking to see if a connection is still active. In fact you won't get anything from this if you use the connection handler. What idle used is to see if the statement handler is still active after execute() is called on it. If you want to check if the connection to the database is still active then you use the $dbh->ping() method.

      if ($dbh->ping()) { $sth = $dbh->prepare('SELECT ...'); $sth->execute(); ... } else { $dbh = DBI::connect(...); }

Re: mysql_auto_reconnect
by Marcello (Hermit) on Jan 27, 2006 at 14:08 UTC
    Just to explain what is happening,

    The connection is lost after wait_timeout seconds of inactivity (SHOW VARIABLES in MySQL). That is why your database connections are closed after this period. You can alter this period in the my.cnf file.