Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Database Update or Insert

by VSarkiss (Monsignor)
on Apr 26, 2002 at 18:46 UTC ( [id://162365]=note: print w/replies, xml ) Need Help??


in reply to Database Update or Insert

The biggest problem with this is what jsprat has pointed out above: you're counting on only getting primary key violations. You should at least check the error condition coming back from the update before blindly trying to insert the row.

The second problem is that you're not taking advantage of one of DBI's best features: placeholders. You're taking the time to prepare the statement, but binding the values directly, which can be a problem if things need quoting. Here's how it would look:

my $sth = $dbh->prepare("UPDATE $table SET upc=? WHERE item_id=?"); # ... if ($sth->execute($upc, $item_id)) { # ...

Some style issues: you're re-declaring $sth in the inner block, masking the outer one, which is unnecessary and can cause confusion in a larger block of code. Finally -- this is just a matter of personal style -- but I find "die-if-not-command" puts the emphasis on the wrong thing. The important part is the command, not the error recovery, which comes through more clearly in this case with "command or die" style.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://162365]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-26 00:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found