Checking for existence in records?

Checking for existence in records?

am 28.03.2005 21:44:02 von KEVIN ZEMBOWER

I'm trying to check if an input record exists in a table, and if it =
doesn't, add it, or if it does, go on to the next input. The code I wrote =
is:
#my $duplangveritem =3D $dbh->selectrow_array("SELECT baseitemid FROM =
langversions WHERE baseitemid =3D'$baseitemid' AND langid=3D'$langid'");
my $sth =3D $dbh->prepare("SELECT baseitemid FROM langversions WHERE =
baseitemid =3D'$baseitemid' AND langid=3D'$langid'");
$sth->execute();
my $duplangveritem =3D $sth->fetchrow_array;

if ($duplangveritem) {
print STDERR "Duplicate item found at line $ln: $_\n";
} else {
my $sth =3D $dbh->prepare("INSERT INTO langversions (baseitemid, =
langid, title, cost, available) VALUES (?, ?, ?, ?, ?)" ) or die "Can't =
prepare statement: $DBI::errstr";
$sth->execute($baseitemid, $langid, $title, $cost, $available)
or die "Can't execute statement: $DBI::errstr";
} # else if there was no duplicate item

I tried both the first, commented-out line, or the next three lines, but =
the line with 'if ($duplangveritem) {' still causes errors like these (the =
'if ($duplangveritem)' line is line 72):
Use of uninitialized value in concatenation (.) or string at ./loadInventor=
y.pl line 72. #NOTE: This is unwanted error
Duplicate item found at line 2: =
#NOTE: This is intended =
output
Use of uninitialized value in concatenation (.) or string at ./loadInventor=
y.pl line 72.
Duplicate item found at line 15:=20

How can I check if the item already exists in the database, and not get an =
error if it doesn't?

Thanks for all your help.

-Kevin Zembower

--
MySQL Perl Mailing List
For list archives: http://lists.mysql.com/perl
To unsubscribe: http://lists.mysql.com/perl?unsub=3Dgcdmp-msql-mysql-modules @m.gmane.org

Re: Checking for existence in records?

am 28.03.2005 21:57:50 von Garry Williams

On Mon, 2005-03-28 at 14:44 -0500, KEVIN ZEMBOWER wrote:
> How can I check if the item already exists in the database, and not get an error if it doesn't?

Insert it and handle the duplicate key error.

This assumes (as you stated) that you want it inserted, if it's not
there. It also eliminates the obvious race condition.

--
Garry Williams, Zvolve Systems, Inc., +1 770 813-4934
Cell: +1 404 353-2983


--
MySQL Perl Mailing List
For list archives: http://lists.mysql.com/perl
To unsubscribe: http://lists.mysql.com/perl?unsub=gcdmp-msql-mysql-modules@m .gmane.org