PDA

View Full Version : postgreSQL - Last Inserted ID



nnidza
26th March 2007, 22:01
I am using QT4.2.3 with PostgreSQL. I am having a following problem.

This is how my table looks like...

[first]

id (sequence) (int8)
fname
lname

When i did...

QSqlQuery query;
query.prepare("INSERT INTO first (fname, lname) VALUES (?, ?)");
query.addBindValue(QString(Fname));
query.addBindValue(QString(Lname))
query.exec();

I got a record inserted in my first table.
But is there any way to retrieve the id after inserting the data in the [first], as it is a sequence?

I have tried using a:

QVariant variant=query.lastInsertId();
int i=variant.toInt();

but I am always getting 0 as a result...
Doing something wrong?

When I try a driver feature It says It is OK.

jacek
26th March 2007, 22:08
You can check the current value of the sequence:SELECT currval('first_id_seq')

nnidza
26th March 2007, 22:13
But what if someone make another transaction in the same time?
I am not an expert but I just thought about it...

jacek
26th March 2007, 22:41
But what if someone make another transaction in the same time?
You'll get the Right(tm) value:

Return the value most recently obtained by nextval for this sequence in the current session. (An error is reported if nextval has never been called for this sequence in this session.) Notice that because this is returning a session-local value, it gives a predictable answer whether or not other sessions have executed nextval since the current session did.

nnidza
2nd April 2007, 08:09
Thank you, it works!