mysql, java - Get last inserted auto increment id from one table and insert it again on another table

前端 未结 1 1464
抹茶落季
抹茶落季 2021-01-27 11:52

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:

相关标签:
1条回答
  • 2021-01-27 12:11

    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.

    0 讨论(0)
提交回复
热议问题