bradcathey has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Testing to INSERT or UPDATE MySQL record
by Solo (Deacon) on Jan 18, 2005 at 18:21 UTC | |
|
Re: Testing to INSERT or UPDATE MySQL record
by dragonchild (Archbishop) on Jan 18, 2005 at 18:25 UTC | |
|
Re: Testing to INSERT or UPDATE MySQL record
by borisz (Canon) on Jan 18, 2005 at 19:45 UTC | |
|
Re: Testing to INSERT or UPDATE MySQL record
by periapt (Hermit) on Jan 18, 2005 at 21:03 UTC |