How to get automatically generated "id" field

From: Nikola Milutinovic <Nikola(dot)Milutinovic(at)ev(dot)co(dot)yu>
To: pgsql-jdbc(at)postgresql(dot)org
Subject: How to get automatically generated "id" field
Date: 2005-03-12 22:24:53
Message-ID: 42336C35.7080003@ev.co.yu
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-jdbc

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.

Responses

Browse pgsql-jdbc by date

  From Date Subject
Next Message Dave Cramer 2005-03-12 23:48:27 Re: How to get automatically generated "id" field
Previous Message Ragnar Hafstað 2005-03-12 09:35:46 Re: [JDBC] MS Access to PostgreSQL