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