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?
Asked
Active
Viewed 8,025 times
5
-
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 Answers
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
-
i get an error saying column id not found when i call rs.getInt("id"); what could be the reason? – Rohit Banga May 18 '10 at 04:56
-
something related. http://bugs.mysql.com/bug.php?id=18409 but even this does not solve the problem – Rohit Banga May 18 '10 at 05:17
-
-
@iamrohitbanga Did you try to retrieve the column by index `rs.getInt(1);`? – Pascal Thivent May 18 '10 at 08:25
-
1yes i did. i still get an exception. i have posted a new question here. http://stackoverflow.com/questions/2854774/sql-jdbc-getgeneratedkeys-returns-column-id-not-found-column-type-unknown – Rohit Banga May 18 '10 at 09:04
-
i have put up the stack trace as well as the datatypes of the columns in the table. see the link above. – Rohit Banga May 18 '10 at 09:05
-