Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

DBI connection springs back to life - how?

by mp (Deacon)
on Jul 26, 2002 at 01:42 UTC ( [id://185398]=perlquestion: print w/replies, xml ) Need Help??

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

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.

Replies are listed 'Best First'.
Re: DBI connection springs back to life - how?
by pope (Friar) on Jul 26, 2002 at 03:48 UTC
    Driver specific behaviour. From DBD::mysql manual:

    DBD::mysql has a "reconnect" feature that handles the so-called MySQL "morning bug":
    If the server has disconnected, most probably due to a timeout, then by default the driver will reconnect and attempt to execute the same SQL statement again.

    However, this behaviour is disabled when AutoCommit is off: Otherwise the transaction state would be completely unpredictable after a reconnect.

      Thank you. The version I was using (2.0419) doesn't have that statement in the docs, but apparently must have that feature as well. I think it's time I upgrade DBD::mysql.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://185398]
Front-paged by cLive ;-)
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (3)
As of 2024-04-26 05:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found