cormanaz has asked for the wisdom of the Perl Monks concerning the following question:
According to postgres docs, including "returning id" in the query should make it return the last id inserted, but it doesn't. If I run this three times I get a "1" returned on each call even though when I look at the DB table I get three records with ids 1,2,3. Anybody know What I am doing wrong?sub insertsql { my ($dbh,$table,$data) = @_; my @qm; my @keys; my @values; my $i = -1; foreach my $k (keys %$data) { if (defined($data->{$k})) { $i++; $keys[$i] = $k; $values[$i] = $data->{$k}; $qm[$i] = '?'; } } my $keylist = join(",",@keys); my $qlist = join(",",@qm); my $sqlstatement = "insert into $table ($keylist) values ($qlist) +returning id"; my $sth = $dbh->prepare($sqlstatement); my $id = $sth->execute(@values) || die "Could not execute statemen +t: $sqlstatement $sth->errstr"; $sth->finish(); return $id; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: How to get inserted id from postgres
by Corion (Patriarch) on Sep 30, 2022 at 20:53 UTC | |
Re: How to get inserted id from postgres
by AnomalousMonk (Archbishop) on Sep 30, 2022 at 22:54 UTC | |
Re: How to get inserted id from postgres
by dsheroh (Monsignor) on Oct 01, 2022 at 12:51 UTC |