in reply to mysql insert/update
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.
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', ;)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; }
|
|---|