Java: How To Get Auto Increment Values After SQL Insert
While inserting a SQL query we do not specify the auto increment values, if any. However they are often required for further processing. Here is how you can obtain auto increment / auto generated values after a successful SQL INSERT statement.
//
// Insert one row that will generate an AUTO INCREMENT
// key in the primary key field
//
stmt.executeUpdate(
"INSERT INTO autoIncTest (comment) "
+ "values ('How can I get the auto increment field value?')",
Statement.RETURN_GENERATED_KEYS);
//
// Use Statement.getGeneratedKeys()
// to retrieve the value(s)
//
int autoIncValue = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
autoIncValue = rs.getInt(1);
} else {
// Error
}
rs.close();
You can also specify and fetch multiple auto-increment key values. This is not just a convenience but a necessity where the primary key is also the auto increment key.
Filed under Database, HSQLDB, Headline News, How To, J2EE, Java Software, Programming, RDBMS |
|
RSS 2.0 |
Trackback this Article
|
Email this Article
You may also like to read |




































June 11th, 2007 at 8:42 pm
This doesn’t work with postgres (at least, when I last tried it). Instead, I use:
PreparedStatement insert = conn.prepareStatement(”insert into thetable (owner, created) values (?,?); select currval(’thetable_id_seq’)”;
…
insert.execute();
if (insert.getUpdateCount() == 1 && insert.getMoreResults()) {
ResultSet res = insert.getResultSet();
int id = res.getInt(1);
}
June 12th, 2007 at 12:34 am
Thanks for sharing. I have tested my code on MySQL.