in reply to Reconnecting to a mysqldb

The connect_cached method does this, but it doesn't do the sleep that you want. To get that, I might just wrap the calls to DBI in an eval and handle the sleep and reconnect at a higher level. It will be less trouble than inheritance.

Replies are listed 'Best First'.
Re^2: Reconnecting to a mysqldb
by jmo (Sexton) on Nov 07, 2006 at 16:26 UTC
    I might be thinking totaly wrong but the reason I'm thinking inheritance is that I have lots of code using plain DBI. With inheritance I'd only need to change the use DBI and $dbh = DBI->connect.

    The only thing (hopefully) I really need to know to get this working is how DBD::mysql does the reconnect (or what it calls) since it can realize the connection is lost and can try to reconnect transparent to the script. Basicly what it does today is:
    $sth = $dbh->prepare ($sql); # im doing a mysql restart $sth->execute (); # DBD::mysql magically reconnects keeping the prepar +ed statement and executes
    While (in case of stoped db):
    $sth= $dbh->prepare ($sql); # stoping mysql $sth->execute (); # DBD::mysql tries, but no connection, reconnecting +and trying again will lose the $dbh->prepare
    So the way I see it it should be a sane and nice way of doing it:
    $sth= $dbh->prepare ($sql); # stoping mysql $sth->execute (); # entering reconnect mode in MyDBI::st/db: while (!$dbh->ping) { sleep 5; MyDBI->connect_like_mysql_reconnects; }
    Prefarable giving arguments like { reconnect_tries => 10, wait_time => 5 } so the scripts can configure themselves how long they are prepared to wait.

    I guess it all boils down to that I think DBI should be responsible for really trying to reconnect and me not having to surround all my db calls with evals, pings and reconnects ...
      Fair enough. I just think you may run into problems if you try to use other tools that want to subclass DBI, like Apache::DBI or Class::DBI. There is an official way to do subclassing, which is discussed in the DBI docs. You can look at the connect_cached() method to see how it handles keeping the connection parameters around.