need help of getting PK after insertRow in JDBC

From: "Chen, Dongdong (GE Healthcare, consultant)" <Dongdong(dot)Chen(at)ge(dot)com>
To: <pgsql-general(at)postgresql(dot)org>, <pgsql-jdbc(at)postgresql(dot)org>
Subject: need help of getting PK after insertRow in JDBC
Date: 2008-09-26 02:14:01
Message-ID: 455802FDAA04064DB56A1D72B2075C9F032E812E@SHAMLVEM02.e2k.ad.ge.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-jdbc

Hi:
I am a software engineer from GE. I am using JDBC to operate
PostgreSQL8.3 in Ubuntu8.04. The develop environment is Eclipse3.2 My
problem is:
There is a PostgreSQL table XX containing 5 fields: AA, BB, CC, DD,
EE, AA is primary key and auto-generated type, BB, CC, DD and EE is
string type.
I want to get the value of AA immediately after insert a row into
the table. the code is like this:

Statement st = db.creatStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs=st.executeQuery("SELECT * FROM XX");
rs.moveToInsertRow();
rs.updateString(BB, "b");
rs.updateString(CC, "c");
rs.updateString(DD, "d");
rs.updateString(EE, "e");
rs.insertRow();
rs.moveToCurrentRow();
int index = rs.getInt("AA");
System.out.println(index);

in the last sentence I always get 0 no matter how many records I
insert. I tried other ways of moving the cursor including next(), last()
and so on, and also cannot get the correct value. I tried the drivers
both postgresql-8.3-603.jdbc3.jar and postgresql-8.3-603.jdbc4.jar.

But when I use pdadminIII to check the table XX, the AA field is
already auto-generated with the correct value.

I found a way to solve this: close resultset and statement after
moveToCurrentRow() and re-open them, and rs.last(), then run int
index=rs.getInt("AA"), I can get the correct value. I think this method
is sort of awkward, anyone knows a better way and the correct
operations?

I am not sure it is proper to send this mail to this mail list. Sorry if
bring you any inconvenience.
Thanks a lot!

Best Regards

Kevin Chen/ChenDongdong
+8613810644051



Responses

Browse pgsql-general by date

  From Date Subject
Next Message Andrew 2008-09-26 02:18:19 Re: Oracle and Postgresql
Previous Message Martin Gainty 2008-09-26 01:49:45 Re: Obfuscated stored procedures (was Re: Oracle and Postgresql)

Browse pgsql-jdbc by date

  From Date Subject
Next Message burferd 2008-09-26 02:21:46 Re: Newby Question - accessing refcursor.
Previous Message burferd 2008-09-26 02:12:56 Re: Newby Question - accessing refcursor.