http://www.perlmonks.org?node_id=929809


in reply to DBI fails to return an error code

Only use $DBI::err (and errstr) when connecting to a database.
Use $dbh->err (and $dbh->errstr) for actions performed using this $dbh.
When working with statement handles (like prepared queries), use $sth->err.
Always try to use the err-function in the smallest scope possible, because the rest can be altered by other parts running in your code (in other threads or wherever).

Replies are listed 'Best First'.
Re^2: DBI fails to return an error code
by mje (Curate) on Oct 05, 2011 at 16:56 UTC

    I'm not entirely sure you are right when you suggest there is a separate err/errstr for each handle. I believe there is only one despite it looking like there is one per handle via the pod.

    perl -le 'use strict; use warnings; use DBI; my $h = DBI->connect("dbi +:mysql:database=test", "xxx","yyy", {RaiseError => 0, PrintError => 0 +}) or die $DBI::errstr; my $s = $h->prepare(q/select * from does_not_ +exist/) or die "prepare: " . $DBI::errstr; $s->execute or print "\nex +ecute DBI:" . $DBI::errstr . " sth:", $s->errstr . " dbh:", $h->errst +r; $h->do(q/rubbish/) or print $s->errstr, "\n"; execute DBI:Table 'test.does_not_exist' doesn't exist sth:Table 'test. +does_not_exist' doesn't exist dbh:Table 'test.does_not_exist' doesn't + exist You have an error in your SQL syntax; check the manual that correspond +s to your MySQL server version for the right syntax to use near 'rubb +ish' at line 1

    Notice you get the same error from DBI, dbh and sth. Also, if you error on a dbh you can access the same error from the sth. I have this recollection from a dbi-dev posting from way back I could probably dig out.

      Initially, all errors are set in $DBI::err. However, since all actions involving DBI (which can be from multiple DBI-sources, multiple databases, multiple queries using the same $dbh, $DBI::err will be overwritten quite a lot.
      To avoid getting an error that is generated by an entirely different bit of code (which runs in another thread/process but shares the DBI environment, or even the $dbh), it is recommended to use the handle with the smallest scope (because that way you can be sure to a much better degree that nothing else has overwritten your errorcode/errorstring).