Fellow Monasterians,
In an attempt to simplify code, I'm trying to figure out a way to test whether or not to INSERT or UPDATE a table that will have only one row. If the table has never been saved to, I want it to INSERT, otherwise if it has the sole record, then UPDATE.
my %sql_data = ( id => 1, message => $message, ); my $sql = qq/UPDATE bankend SET / . join(' = ?,', keys %sql_data) . qq +/ = ? /; $sth = $dbh->prepare($sql) or die "prepare: $stmt: $DBI::errstr"; if (!$sth->execute(values %sql_data)) { $sql = qq/INSERT INTO bankend (/ . join(',', keys %sql_data) . qq/) + VALUES (/ . join(',', ('?') x keys %sql_data) . qq/)/; $sth = $dbh->prepare($sql) or die "prepare: $stmt: $DBI::errstr"; $sth->execute(values %sql_data) or die "execute: $stmt: $DBI::errst +r"; }
Right now, when I run it, it does neither—the table remains empty. As you see, I'm testing (I believe) for the error when it tries to update the "existing" row, when it actually has not been created. Thanks.
In reply to Testing to INSERT or UPDATE MySQL record by bradcathey
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |