cormanaz has asked for the wisdom of the Perl Monks concerning the following question:
I'm now working with Postgres and, alas, there is no 'mysql_insertid' for postgres, and it doesn't provide such an easy way to get the inserted id.sub insertsql { my ($dbh,$table,$data,$ignore) = @_; 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)" +; if ($ignore) { my $sqlstatement = "insert ignore into $table ($keylist) value +s ($qlist)"; } my $sth = $dbh->prepare($sqlstatement); #$sth->execute(@values) || die "putsql could not execute MySQL sta +tement: $sqlstatement $sth->errstr"; $sth->execute(@values) || die $sth->errstr; $sth->finish(); return $dbh->{'mysql_insertid'}; }
I found this thread on Stack Overflow where somebody suggests using a separate statement SELECT currval(pg_get_serial_sequence('[tablename]','id')) but that returns nothing. They also suggest adding returning id to the end of the insert statement. But I can't figure out how to make that work in the context of the subroutine.
Can anyone help?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Getting id of postgres record inserted via DBI
by cavac (Prior) on Jun 22, 2023 at 06:43 UTC | |
by erix (Prior) on Jun 22, 2023 at 16:19 UTC | |
by marto (Cardinal) on Jun 22, 2023 at 16:21 UTC | |
by cavac (Prior) on Jun 26, 2023 at 08:26 UTC | |
by erix (Prior) on Jul 04, 2023 at 09:11 UTC | |
| |
Re: Getting id of postgres record inserted via DBI
by soonix (Chancellor) on Jun 22, 2023 at 06:48 UTC | |
Re: Getting id of postgres record inserted via DBI
by ikegami (Patriarch) on Jun 22, 2023 at 13:19 UTC |