Reconnecting to Database in a script

D

dn_perl

I run a perl script which uses an infinite loop.
I would like to incorporate checks which allow me to exit
the infinite loop if the database is brought down.

The current script is :

----------------
$dbh = DBI->connect or die ;
while(1) {
do certain things ;
if( str eq 'this' ) { # check one
last;
}
# I want to add check # two here
sleep 100 ;
}
$dbh->disconnect ;
----------------

What should check # two do?
Would the following statement work?
if( not $dbh ) { last ; }
I don't know how $dbh is affected when the databse is brought down.
And I have no way of knowing it right now.


===========================
 
S

Sherm Pendley

Would the following statement work?
if( not $dbh ) { last ; }
I don't know how $dbh is affected when the databse is brought down.

It probably isn't immediately affected at all - a client generally
doesn't maintain a persistent connection to the DB, so won't know the
server is down until it tries to connect to it and run a query.

Fortunately, DBI provides a ping() method for checking the server's status:

if ( not $dbh->ping() ) { last; }

sherm--
 
T

Tore Aursand

I run a perl script which uses an infinite loop.
I would like to incorporate checks which allow me to exit
the infinite loop if the database is brought down.

Do you really want to do that? Why don't you want to reconnect to the
database?
$dbh = DBI->connect or die ;
while(1) {
do certain things ;
if( str eq 'this' ) { # check one
last;
}
# I want to add check # two here
sleep 100 ;
}
$dbh->disconnect ;

Check #2 could be something like this;

last unless ( $dbh->ping() );

However, I would have written this routine like this (and then have my
script reconnect to the server if the connection is lost):

my $dbh = undef;
while ( 1 ) {
unless ( defined $dbh || $dbh->ping() ) {
# Connect
}
# The rest of the loop
}
$dbh->disconnect if ( defined $dbh && $dbh->ping() );
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top