我认为这个问题总结得很好,这是我目前的代码,但它没有给我所需的结果。我想返回一个 int 数组,其中包含为该批次中创建的每一行生成的自动增量 ID。
CREATE_APPOINTMENT = database.prepareStatement("INSERT INTO " + TABLE_APPOINTMENTS + " VALUES (?, ?, ?, ?, ?)");
public static int[] createAppointment(Appointment... appointments) {
int[] ids = new int[appointments.length];
int count = 0;
try {
for (Appointment a : appointments) {
CREATE_APPOINTMENT.setDate(2, a.date);
CREATE_APPOINTMENT.setTime(3, a.time);
CREATE_APPOINTMENT.setInt(4, a.duration);
CREATE_APPOINTMENT.setString(5, a.clientName);
CREATE_APPOINTMENT.addBatch();
}
CREATE_APPOINTMENT.executeBatch();
ResultSet resultSet = CREATE_APPOINTMENT.getGeneratedKeys();
if (resultSet != null)
while (resultSet.next()) {
ids[count++] = resultSet.getInt(1);
}
} catch (SQLException ex) {
System.err.println(ex);
}
return ids;
}
我尝试创建 8 个约会,并且根据数据库成功创建了他们的 id,但我的返回数组只包含最后一个 id,其余的都是零。我在哪里错过了什么?