Reconnecting to a database
am 07.11.2006 10:57:21 von jon.molinHi list,
I have a long running script that needs to be able to reconnect to the
database (mysql) since the db is restarted sometimes. My plan was to
subclass DBI (like in the t/ dir) and add checks in execute and the
fetch methods of MyDBI::st, and if the DB has gone away reconnect and
re-run the prepare and then execute.
I've reached the point where I do execute and see that the DB is gone.
My problem is that at that point (in the MyDBI::st::execute) is all I
have a reference to myself, not to the dbh used to do the prepare so
what I wonder is how should I go about changing the handle? What I've
don is basicly:
package MyDBI;
use strict;
use DBI;
use DBD::mysql;
use vars qw(@ISA);
@ISA = qw(DBI);
sub connect
{
my $self = shift;
my ($dsn, $uname, $passwd) = @_;
my $this = $class->SUPER::connect($dsn, $uname, $passwd);
$this->set_dsn ($dsn, $uname, $passwd); # so I can reconnect easily
return $this;
}
package MyDBI::db;
@MyDBI::db::ISA = qw(DBI::db);
my ($_uname, $_passwd, $_dsn);
sub set_dsn
{
my $this = shift;
($_dsn, $_uname, $_passwd) = @_;
}
sub reconnect
{
# somthing like MyDBI->connect ($_dsn, $_uname, $_passwd);
# and then rerun prepare
}
package MyDBI::st;
@MyDBI::st::ISA = qw(DBI::st);
sub execute
{
my $this = shift;
$this->SUPER::execute (@_);
if ($this->errstr =~ /server has gone away/)
{
MyDBI::db->reconnect;
# and then rerun execute with some sleep to avoid insane bahviour
}
}
1;
So basicly, my problem is that my script calling here has a dbh and i
need that to be changed...
Thanks
/jon