I think the question sums it up well enough, here’s my code at the moment but it’s not giving me the required results. I want to return an int array containing the generated auto-increment id’s for each row created in that batch.
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;
}
I’ve tried creating 8 appointments and their id’s are created successfully according to the database but my returns array only contains the last id and the rest are zeros. Where am I missing something?
Actually it is impossible. stmt.getGeneratedKeys() will always return only one value because this method in sqlite-jdbc driver is implemented so:
ResultSet getGeneratedKeys() throws SQLException { if (getGeneratedKeys == null) getGeneratedKeys = conn.prepareStatement("select last_insert_rowid();"); return getGeneratedKeys.executeQuery(); }Your array is initialized with zero values, and then the last generated id is assigned to the first element of array.