简体   繁体   中英

Get generated keys from single insert statement with multiple values

i'm inserting multiple rows into a table using a single insert statement. The table has an auto increment field as the primary key.

Like so: INSERT INTO MyTable VALUES (?,?,?,?),(?,?,?,?),(?,?,?,?),(?,?,?,?)

StringJoiner sj = new StringJoiner(",");
for(int i=0;i<salesmen.size();i++)
    sj.add("(?,?,?,?)");

sql.append("INSERT INTO MyTable ");
sql.append("VALUES ");
sql.append(sj.toString());

try(PreparedStatement statement = connection.prepareStatement(sql.toString(),Statement.RETURN_GENERATED_KEYS)){
    int i = 1;
    for(Salesman salesman : salesmen){
        statement.setDate(i++, DateUtil.toSqlDate(date));
        statement.setString(i++, salesman.getName());
        statement.setInt(i++, salesman.getWeeklyTargetCustomerId());
        statement.setInt(i++, salesman.getCycle());
    }
    statement.executeUpdate();

    ResultSet generatedKeys = statement.getGeneratedKeys();
    while(generatedKeys.next()) {
        log.info("generated key: " + generatedKeys.getLong(1)); //only prints 1 id
    }
}
catch(SQLException e){
    log.info("(!!) SQL Exception in Execution: " + e.getMessage());
    log.info("\n\n" + sql.toString() + "\n");
}

When i call getGeneratedKeys() , it returns a ResultSet with only the id of the last row inserted, and not all of the rows. If i insert 50 rows, how do i obtain a resultset with 50 generated keys?

Although it's an old question, I hope it helps someone.

PreparedStatement pre = connection.prepareStatement("SQL", PreparedStatement.RETURN_GENERATED_KEYS);
for(Salesman salesman: salesmen) {
    pre.setString(i++, ...);
    pre.setString(i++, ...);
    ....
    pre.addBatch(); // Add this
}
pre.executeBatch(); // Add this
ResultSet rs = pre.getGeneratedKeys();
while(rs.next()) {
    int id = rs.getInt(1); // This should contain the id of the inserts in order.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM