On Fri, Apr 12, 2002 at 06:55:05AM -0400, Condle, Joseph P wrote:

> The following is an insert script I working on.  I need to trap the
> unique constraint error and send a message back to the user.  I am really
> confused.  I have read the error handling chapter of the O'reilly Perl
> DBI book, but I just don't get it.  I must have some kind mental block.
> If I could get a working example hopefully the light will come on.  This
> will eventually work with a html Form.

There are two ways to catch DBI errors and output your own error messages.
First of all, either way you want PrintError *off*.  Then, you can leave
RaiseError off, and check for errors after each statement, or turn
RaiseError on, and use eval {} to catch any errors from a series of
statements.


With RaiseError off:

my $sth = $dbh->prepare("INSERT INTO mytable VALUES (?, ?)");

if (!$sth) {
  print "Error preparing insert statement: $DBI::errstr\n";
}

my $rc = $sth->execute($val1, $val2);
if (!$rc) {
   print "Error inserting new row: $DBI::errstr\n";
}


With RaiseError on:

eval {
  my $sth = $dbh->prepare("INSERT INTO mytable VALUES (?, ?)");

  $sth->execute($val1, $val2);
};

if ($@) {
   print "An error occured: $@\n";
}


Ronald

Reply via email to