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.


In reply to Re: Database Update or Insert by VSarkiss
in thread Database Update or Insert by Mr. Muskrat

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.