in reply to What to do when DBI connect fails

Your idea is correct in that $dbh will be defined if the connect() succeeds.

As a fundamental question: What do you intend to do if the connect fails?

I would probably loop back to the original connect() statement with an escape value of some max number of "try this other thing" statements or some other limiting factor.

With SQLite, basically it comes down to whether you have permission to access the file or not. There are no user name or password issues like with a normal server and that is a cool thing.

I would be thinking along the lines of checking if the file and path are valid and then do whatever you have to do if that is not right. What I don't know... After that let the program "blow up" if the connect fails (and that would mean corrupted .db file). Anyway what you intend to do if the connect fails is relevant.

Replies are listed 'Best First'.
Re^2: What to do when DBI connect fails
by YordanGeorgiev (Acolyte) on Jan 07, 2019 at 21:10 UTC
    # # ----------------------------------------------- # open the database handle if possible, if not return proper error +msgs # ( $ret , $msg , $dbh ) = $self->doConnectToDb ( $db ) ; # ----------------------------------------------- sub doConnectToDb { my $self = shift ; my $db = shift || 'non_accessible_db' ; my $ret = 400 ; my $msg = 'cannot connect to the "' . $db . '" database: '; my $dbh = undef ; $dbh = DBI->connect("dbi:Pg:dbname=$db", "", "" , { 'RaiseError' => 0 # otherwise it dies !!! , 'ShowErrorStatement' => 1 , 'PrintError' => 1 , 'AutoCommit' => 1 , 'pg_utf8_strings' => 1 }) ; if ( defined $dbh ) { $ret = 0 ; $msg = "" ; } else { $msg .= DBI->errstr ; } return ( $ret , $msg , $dbh ) ; }