Connecting to multiple databases in a perl script

How can I connect to multiple databases in perl without saving it if it cannot connect to one? If I have the database names in the array and loop through them, I want to try to connect and execute the query and disconnect. I am going to report this to the big brother monitoring page. I do not want the script to end if it cannot connect to it, since it obviously needs to check everything in the array. Right now I am using the DBI modules state method, but I do not know that it works correctly. Thanks for all the time!

0
source share
3 answers

Can we see the code? I do not think the call DBI->connect()will die unless you explicitly report it, as in:

DBI->connect($dsn, $user, $pass) or die "Can't connect: $DBI::errstr\n";

I am sure that even using {RaiseError => 1} will not make him die automatically. So, if you call or die..., just don't do it!

EDIT:

Given the code that @squiguy sent, I would do it like this:

foreach my $host (@hosts) { 
    $dbh = DBI->connect("dbi:Oracle:; host=$host; port=$port", $username, $password); 
    next unless $dbh;
    if ($dbh->state()) {
        # Do stuff with state information
    }
}
+1
source

You should look for exception handling in Perl. I don't use Perl, so I don't know the syntax for handling exceptions, it should be easy enough to find on the Internet, though.

0
source

, .

, . , .

perl , ?

, . eval , - Perl, .

- :

for my $database (@database_list)  {
   my $dbh;
   eval {
       $dbh = DBI->connect($database, $user, $password);
   };
   if (not $@) {
        yadda, yadda, yadda
   }
}

eval . $@ , , eval - . $@ , , .

HOWEVER . By default, the DBI does not die automatically if it cannot connect. Instead, it simply returns undefined. You should be able to use this to determine if you have succeeded, or if you need to go to the following database:

           for my $database (@database_list)  {
   my $dbh = DBI->connect($database, $user, $password);
   if ($dbh) {
        yadda, yadda, yadda
   }
}

If I remember correctly, there is a RaiseError attribute , which, if set, will cause your program to die if the DBI call fails. However, the default value should not be set, so you should not have a problem.

0
source

Source: https://habr.com/ru/post/1626495/


All Articles