From: Nikola Milutinovic <Nikola.Milutinovic@ev.co.yu>
To: pgsql-jdbc@postgresql.org
Subject: How to get automatically generated "id" field
Date: Sat, 12 Mar 2005 23:24:53 +0100
Message-ID: <42336C35.7080003@ev.co.yu> (raw)
Hi all.
This may be a bit more for general ML, but I'm in a fix and need an
advice. I have several tables with auto-generated "id" field, like this.
CREATE TABLE photo (
id SERIAL PRIMARY KEY,
size INT8,
file VARCHAR(256)
)
I would like to be able to insert values and get back the "id" of a
newly inserted record. What is a good way to do it?
I imagine I could open a transaction and read the value of the sequence,
but that is ugly, since the sequence name is autogenerated and PG specific.
Would it be better to change "SERIAL" to just INT8 and do in a transaction:
...start transaction
executeQuery( "SELECT max( id )+1 AS new_id FROM photo" );
..read "new_id"
executeUpdate( "INSERT INTO photo (id, size, file) VALUES (...)" );
..commit
Nix.
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-jdbc@postgresql.org
Cc: Nikola.Milutinovic@ev.co.yu
Subject: Re: How to get automatically generated "id" field
In-Reply-To: <42336C35.7080003@ev.co.yu>
References: <42336C35.7080003@ev.co.yu>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox