Tuesday, December 15, 2009

Getting the auto increment id from SQL insert in Java

Often you need the id or autoincremented values of a row you have inserted into the database. To get this in Java do the following:
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);


The key here is the Statement.RETURN_GENERATED_KEYS. Now you can get the auto incremented keys by doing the following:
rs= stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);


It's also possible to do this with regular statements (not prepareStatements) like this:
stmt = conn.createStatement();
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);


Solution source: http://stackoverflow.com/questions/1376218/is-ther-a-way-to-retrieve-the-autoincrement-id-from-a-prepared-statement

No comments:

Post a Comment