5

I have a primary key auto increment attribute in my table. I want to know the value assigned to it for a row that is inserted using statement.executeUpdate(). How to achieve this in the best possible manner?

Rohit Banga
  • 18,458
  • 31
  • 113
  • 191
  • For what database? You could use the RETURNING clause for Oracle/DB2 (and possibly Postgres); LAST_INSERT_ID for MySQL; @SCOPE_IDENTITY for SQL Server... – OMG Ponies May 17 '10 at 21:50
  • @OMGPonies: JDBC abstracts the way databases implement this (when supported by the database). – Pascal Thivent May 17 '10 at 21:57

1 Answers1

12

Use Statement#getGeneratedKeys() and Statement#executeUpdate(String, int) (this is a JDBC 3.0 feature, your database has to support JDBC 3.0).

Here's an example that returns a ResultSet with values for auto-generated columns in TABLE1:

Statement stmt = conn.createStatement();
int rows = stmt.executeUpdate("INSERT INTO TABLE1 (C11, C12) VALUES (1,1)", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124