When I run the following code, if I stop the database server wait a few seconds, then start it again, the very next query after the surver comes back up (and all subsequent queries) work. Apparently DBI transparently reconnects to the MySQL server as soon as it comes back up. Can anyone explain why or how it does this? Is this auto-reconnect behavior reliable in a production environment? If so, then it makes
Problem managing persistent database connections in modules obsolete. Is there anything (other than a
$dbh->disconnect) that would prevent the auto-reconnect from occurring?
my ($user, $password, $dsn); ### Set these to run code
my $sql = "select * from tablename where id=?";
use strict;
use warnings;
use DBI;
my $dbh = DBI->connect($dsn, $user, $password, {RaiseError => 1});
my $sth = $dbh->prepare($sql);
my $result;
for(1..1000) {
eval {
$result = &simple_query;
};
if ($@) {
print "Found error [$@]\n";
} else {
use Data::Dumper;
warn Dumper($result);
}
sleep 1;
}
sub simple_query {
$sth->execute(int(rand(7000)));
my $ref = $sth->fetchrow_hashref or return;
return $ref;
}
The output while the server is down looks like:
DBD::mysql::st fetchrow_hashref failed:
fetch() without execute() at ./db_connect line 31.
Found error DBD::mysql::st fetchrow_hashref failed:
fetch() without execute() at ./db_connect line 31.
The output when it comes back up looks like normal
Data::Dumper results from a hash.