its duplicate question with Get last inserted auto increment id in mysql
I\'m creating a group it insert on M_GROUPS
.
M_GROUPS
table:
Use getGeneratedKeys() method from your Statement
object to identify the new auto generated values. Iterate the returned ResultSet
object to get the newly generated key values in the order of batch statements.
Change:
stmt.executeUpdate(sql);
To:
int rowsAffected =
stmt.executeUpdate( sql, Statement.RETURN_GENERATED_KEYS );
ResultSet rs = stmt.getGeneratedKeys();
//******************************************************
// in case of batch insert, you can check how many are inserted
rs.last();
int rows = rs.getRow();
System.out.println( "Generated keys count: " + rows );
//******************************************************/
int currentRow = 1;
rs.beforeFirst();
while( rs.next() ) {
System.out.println( /**/( currentRow++ ) + " = " + /**/rs.getInt( 1 ) );
} // while rs
Once you have this auto generated key value in a variable, you can use it with other SQL statements, to store in other tables.
Note: Call to getGeneratedKeys()
may throw java.sql.SQLFeatureNotSupportedException, if the JDBC driver, that you are using, does not support this method.