in reply to Handling a Database Error

semi-psuedo code
my $q = 'INSERT INTO some_table (data) VALUES (?)'; my $sth = $dbh->prepare($q); while(my $data = $csv->get_next_line()) { eval{ $sth->execute($data); } if($@) { next; } # More code here... }

Replies are listed 'Best First'.
Re^2: Handling a Database Error
by dragonchild (Archbishop) on Sep 30, 2005 at 18:01 UTC
    You'll need to set local $dbh->{RaiseError} = 1; above your while-loop for that to guarantee working in all situations. And, since you're using local, I'd recommend a bare-block.
    my $q = 'INSERT INTO some_table (data) VALUES (?)'; my $sth = $dbh->prepare($q); { local $dbh->{RaiseError} = 1; while(my $data = $csv->get_next_line()) { eval{ $sth->execute($data); } if($@) { next; } # More code here... } }

    Of course, with RaiseError set to false, you can also do the more readable:

    while ( my $data = ... ) { $sth->execute( $data ) or next; }
    It's up to you and the style you choose to work with. Either way, be consistent. (You wrap your execute(), but not your prepare() ... tsktsk!)

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
Re^2: Handling a Database Error
by k_rajesh (Sexton) on Sep 30, 2005 at 19:57 UTC
    On my Microsoft Access database the following works:
    #Check for duplicate insert into database. if ($dbh->errstr()=~/SQL-23000/) { $template->param(duplicate => 1); }
    If during debug, you set $dbh->{RaiseError} =1, your logs will show what errstr MySQL is throwing... checking for that (instead of SQL-23000 as in my case) should fix this issue...

    2005-10-01 Retitled by Chady, as per Monastery guidelines

Re^2: Handling a Database Error
by pg (Canon) on Sep 30, 2005 at 20:14 UTC

    Instead of doing "if ($@)", it is better to do what r_rajesh suggested. Although you want to ignore the duplicate key situation, you still want to deal with other errors.