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.

In reply to DBI connection springs back to life - how? by mp

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.