user356135
user356135

Reputation: 21

If Database connection failed try to reconnect

I am newbie to perl , My scenario is m having an array of host , In a loop i am creating DNS and connection to database . But if any host is not responding or down , then that loop is getting break and remaining host not able to connect , My question is how can i skip that means if any host is not able to connect then i want to skip that host and want to connect with other one... Hi all , I am newbie to perl , My scenario is m having an array of host .

In a loop i am creating DNS and connection to database . But if any host is not responding or down , then that loop is getting break and remaining host not able to connect .

My question is how can i skip that means if any host is not able to connect then i want to skip that host and want to connect with other one...Or try to reconnect that host again ...

snippet of code is given bellow


@arr_ =('host1','host2');
foreach $host (@arr_){
   @Mydsn =("dbi:mysql:$MYSQL_DATABASE:$host:$MYSQL_PORT","$MYSQL_USER","$MYSQL_PWD");

my $my_connection = DBI->connect(@Mydsn, { RaiseError => 0, PrintError => 1 } ) or die("Fail to connect Database connection"); ### Here how can i skip if mysql is not able to connect with breaking execution of script

}

Please help me out ! Thanks in advance Please help me out ! Thanks in advance

Upvotes: 0

Views: 1089

Answers (2)

Juan
Juan

Reputation: 1540

Maybe you can check if the server is alive first, something similar to:

use IO::Socket::INET;
@arr_ =('host1','host2');
foreach $host (@arr_) {
    $sk = IO::Socket::INET->new(PeerAddr => $host, 
                                PeerPort => '5432', # if postgres
                                Proto    => 'tcp' );
    if ($sk) {
        my $my_connection =  DBI->connect(@Mydsn, { RaiseError => 0, PrintError => 1 } ) 
                 or die("Fail to connect Database  connection");
    } 
}

Upvotes: 0

Tim
Tim

Reputation: 14154

die immediately stops the script. Use next instead. Adapting your code above:

my @arr = ('host1','host2');
foreach my $host (@arr){
    my @mydsn = ("dbi:mysql:$MYSQL_DATABASE:$host:$MYSQL_PORT","$MYSQL_USER","$MYSQL_PWD");
    my $my_con = DBI->connect(@Mydsn, { RaiseError => 0, PrintError => 1 } );
    if ( ! $my_con ) {
        warn "failed to connect to $host";
        next;
    }
}

In this simple case, next is of course unnecessary.

Upvotes: 2

Related Questions