'update;insert if update did not update' makes the most sense if the majority of your queries are updates; it means that most of the time you are doing a single query, whereas 'select;insert or update based on select result' means you always do two queries regardless.

The only problem is that mysql has an optimization such that if you update a row with the values it already has, it will not do the update and return 0 rows modified. I work around this by using the mysql_client_found_rows option. That tells mysql to always return the number of rows matched.

my $dbh = DBI->connect( "DBI:mysql:database=$db_name;host=$DB_HOST;mysql_client_found_rows=1 +", "$DB_USER", "$DB_PASS" ) or die $DBI::errstr; my $rows = $dbh->do(qq~ update mytable set myvalue = ? where mykey = ? ~, undef, $myvalue, $mykey ) or die $DBI::errstr; if ($rows == 0) { # no record updated, so we insert new one $dbh->do(qq~ insert into mytable values ( ?, ? ) ~, undef, $mykey, $myvalue ) or die $DBI::errstr; }
Note that do() returns 0E0 which == 0, but is still true. Also note that when using this method, the order of the bound vars are often swapped in the insert since the key or keys are last in the update sql. This code is also cool because it says 'do or die', ;)

In reply to Re: mysql insert/update by dkr
in thread mysql insert/update by rsiedl

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.