http://qs321.pair.com?node_id=218402


in reply to Detecting a failed DBI connection

It looks like you might need to add some error checking to your program. Something like the following will display the error text if the connection fails.

$dbh = DBI->connect("DBI:...", $user, $passwd) or print "<p>Error connecting to database: " . $dbh->errstr . "</p +>", exit;

Look around the monastery for DBI tutorials. I've seen a few but don't have any bookmarks handy.

Replies are listed 'Best First'.
Re: Re: Detecting a failed DBI connection
by Massyn (Hermit) on Dec 08, 2002 at 23:03 UTC

    #!/fellow/monks.pl

    Thanks! You put me on the right track, but the code didn't work. For some reason, $dbh->errstr doesn't cut it. I looked it up, and found that $DBI::errstr did the trick.

    Thanks!

    #!/massyn.pl

    You never know important a backup is until the day you need it.

Re: Re: Detecting a failed DBI connection
by chromatic (Archbishop) on Dec 09, 2002 at 00:08 UTC

    If $dbh isn't defined, call errstr() on it? :)

      oops!

Re: Re: Detecting a failed DBI connection
by mt2k (Hermit) on Dec 09, 2002 at 03:32 UTC
    I'm just wondering as to whether your way of printing out errors to the browser is efficient. For starters, this is really just reinventing the fatalsToBrowser method provided by the CGI::Carp module. I could understand this if maybe you didn't want all errors to be outputted to the user's browser. But even at this point, you'd have to make sure that HTTP headers have already been sent to the browser, otherwise your code would just damage the output. If you're set on using this, maybe a subroutine call would be more appropriate, so that you can later change the error handling behaviour. Besides, then you won't have ugly exit() calls hanging around everywhere :)

    mt2k -> must try 2 know

      I wouldn't write code this way but the user's example had not used the CGI module and had already put out the http header. The original poster wanted to know how to find out what went wrong so I plugged an [unfortunately broken] example of how to find out into his code. I guess I could have gone on to give a couple of pointers on better ways to structure his web apps and rewritten his entire snippet for him but I thought he's already having problems with DBI, why confuse him with talk about CGI? Hopefully, he'll get there when he's ready for it.