PyPGSQL - OID

M

Manuel Huesser

Der Python DB API supports the method oidValue on a cursor instance.
On PostgreSQL I get the internal used oid from each row, but I need
the id from the primary key. Is there a way?

Thanks
 
M

Michael Fuhr

Manuel Huesser said:
Der Python DB API supports the method oidValue on a cursor instance.
On PostgreSQL I get the internal used oid from each row, but I need
the id from the primary key. Is there a way?

If you're setting the primary key from a sequence then you can
use CURRVAL('sequence_name'). For example, suppose you have
this table:

CREATE TABLE person (
id SERIAL PRIMARY KEY,
name VARCHAR(64) NOT NULL
);

PostgreSQL will create a sequence named person_id_seq that will
be used to populate the id field (the primary key). After an
INSERT, you can use CURRVAL('person_id_seq') to refer to the
primary key:

curs.execute("INSERT INTO person (name) VALUES (%s)", ["Guido"])
curs.execute("SELECT * FROM person WHERE id = CURRVAL('person_id_seq')")
print curs.fetchone()

CURRVAL() returns the most recently used sequence number in the
current connection, so you don't need to worry about the value
being incremented by other connections before you get a chance
to query it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top