yoda54 has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, How can I prevent my script from bombing if the host I'm quering is not up. my $dsn = "DBI:mysql:host=192.168.1.100:database=testdb"; I want to do something like this but my script exits out: if ($UP) { Query blah blah; } else { Read from file; } Thanks

Replies are listed 'Best First'.
Re: DBI connections.
by ColtsFoot (Chaplain) on Dec 12, 2003 at 08:01 UTC
    From perldoc DBI
    $dbh = DBI->connect($dsn, $user, $password, { RaiseError => 1 }); "RaiseError" (boolean, inherited) This attribute can be used to force errors to raise excepti +ons rather than simply return error codes in the normal way. It + is "off" by default. When set "on", any method which results +in an error will cause the DBI to effectively do a "die("$class $ +method failed: $DBI::errstr")", where $class is the driver class a +nd $method is the name of the method that failed. E.g., DBD::Oracle::db prepare failed: ... error text here ... If you turn "RaiseError" on then you'd normally turn "Print +Error" off. If "PrintError" is also on, then the "PrintError" is +done first (naturally). Typically "RaiseError" is used in conjunction with "eval { +... }" to catch the exception that's been thrown and followed by a +n "if ($@) { ... }" block to handle the caught exception. In that + eval block the $DBI::lasth variable can be useful for diagnosis +and reporting. For example, $DBI::lasth->{Type} and $DBI::lasth->{Statement}.
    Hope this helps
Re: DBI connections.
by davido (Cardinal) on Dec 12, 2003 at 07:53 UTC
    Is the program termination the result of a die somewhere within the module you're using to query the host? If so, you can probably trap the event by wrapping your query in an eval block. Then examine the contents of $@ to ensure whether or not the query caused an otherwise fatal error.

    I could be way off. But often you can innoculate your script from the grim reaper of death by trapping him inside an eval. ;)


    Dave

Re: DBI connections.
by chimni (Pilgrim) on Dec 12, 2003 at 11:21 UTC


    you can use raiseerror
    you can use warn if you want to raise a connection alert but do not want to exit.
    you can have a "crude implementation" of pinging the server and using a if ( my $output =~ m/ping positive output on your operating system) { query }.
    HTH