我使用单个insert语句将多行插入表中。该表有一个自动增量字段作为主键。
像这样: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");
}
当我调用getGeneratedKeys()
时,它返回一个ResultSet
,其中只插入了最后一行的id,而不是所有行。如果我插入50行,我如何获得50个生成密钥的结果集?
答案 0 :(得分:1)
虽然这是一个老问题,但我希望它对某人有所帮助。
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.
}