0

Possible Duplicate:
How to get the insert ID in JDBC?

In the following statement, how can I fetch the last inserted C12 identity value? This is from the JavaDB manual, but they have not mentioned how to retrieve this last inserted value from this record set.

CREATE TABLE TABLE1 (C11 int, C12 int GENERATED ALWAYS AS IDENTITY)

Statement stmt = conn.createStatement(); 
stmt.execute(
    "INSERT INTO TABLE1 (C11) VALUES (1)",
    Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
Community
  • 1
  • 1
Sam
  • 2,702
  • 5
  • 31
  • 45

1 Answers1

2

Here's an example to get generated keys:

ResultSet rs = statement.getGeneratedKeys();
if (rs != null && rs.next()) {
    key = rs.getLong(1);
}

PS: A related StackOverflow question can suffice.

Community
  • 1
  • 1
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
  • It never returns `null`. – BalusC Oct 27 '11 at 14:48
  • Fair enough! :-) it's old habit. – Buhake Sindi Oct 27 '11 at 17:26
  • @BalusC : Only if the driver is implemented properly, otherwise it might return null :) BTW: if rs.getLong(1) returns the actual key depends on how the JDBC driver is implemented: some databases will return *all* columns when using RETURN_GENERATED_KEYS (eg PostgreSQL does) – Mark Rotteveel Oct 28 '11 at 08:37
  • @Mark: that would violate the javadoc: http://download.oracle.com/javase/6/docs/api/java/sql/Statement.html#getGeneratedKeys%28%29 The `ResultSet` has either a key or is empty. Or a `SQLException` will be thrown. – BalusC Oct 28 '11 at 10:35
  • The javadoc can claim a lot, but if the driver implementer didn't read it properly it can return null (I know because I recently fixed exactly such a bug in Jaybird). Especially as the similar getResultSet() method *can* return null. – Mark Rotteveel Oct 28 '11 at 10:52