Reconnecting to a database

Reconnecting to a database

am 07.11.2006 16:09:02 von jon.molin

Hi List,

Sorry if this turns out to be a double post, I mailed this question a
few hours ago but haven't got it myself.

I have a script that runs over a long period of time. During this time
the database (mysql) might shut down for maintance/backup and I want
the script to survive that. The way I want to handle it is "if
connection closed sleep a while, try to reconnect and then try again"
a few times (the server is normaly down for 2s-2minutes. That is,
basicly I want it to act like mysql_auto_reconnect except I also want
it to handle if the server is down when it tries to reconnect instead
of giving up there.

To solve this did I make a subclass of DBI and override execute/fetch*
in DBI::st. Now, my problem is that I, of course, get an DBI::st
object into MyDBI::st->execute and I want to basicly do:
package MyDBI::st;
@MyDBI::st::ISA = qw(DBI::st);

sub execute {
my $this = shift;
if (!$this->{DataBaseHandle}->ping)
{
while (!$this->{DataBaseHandle}->ping))
{
#reconnect && last;
sleep 5;
}
# undo old prepare to avoid possible
# re-run prepare
}
return $this->SUPER::execute (@_);
}


so when i call:
$sth->execute (@bind_params);
will $dbh in the script scope be reconnected and the query (and
further queries) will play nicely.

I know I could make some (imho) ugly hack around it all but I think
it'd be a lot neater doing this way, and it'd be alot easier replacing
code using DBI to use my subclass...

/Jon