I am trying to get last inserted row id while inserting using JDBC prepared statements. I have an auto increment primary key column as identity column in table. My code is below:
public static String insertMeetingToDB(String organizer,String subject,String location,String start_date_time,String end_date_time,String description) throws Exception {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
Integer last_inserted_id=0;
String insertTableSQL = "INSERT INTO MEETINGS"
+ "(ORGANIZER_EMAIL, SUBJECT, MEETING_LOCATION, START_DATE_TIME, END_DATE_TIME, MEETING_DESCRIPTION) VALUES"
+ "(?,?,?,?,?,?)";
SimpleDateFormat from = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
from.setTimeZone(TimeZone.getTimeZone("IST")); //--CONVERTING DATE/TIME TO INDIAN STANDARD TIME
SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
Date input_start_date_val = from.parse(start_date_time);
Date input_end_date_val = from.parse(end_date_time);
String input_start_date = datetimeFormat.format(input_start_date_val);
String input_end_date = datetimeFormat.format(input_end_date_val);
try {
dbConnection = getConnection();
//--INSERTING MEETING DETAILS
preparedStatement = dbConnection.prepareStatement(insertTableSQL, preparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, organizer);
preparedStatement.setString(2, subject);
preparedStatement.setString(3, location);
preparedStatement.setTimestamp(4, java.sql.Timestamp.valueOf(input_start_date));
preparedStatement.setTimestamp(5, java.sql.Timestamp.valueOf(input_end_date));
preparedStatement.setString(6, description);
// execute insert SQL stetement
preparedStatement.executeUpdate();
ResultSet rs = preparedStatement.getGeneratedKeys();
if(rs.next())
{
last_inserted_id = rs.getInt(1);
}
return last_inserted_id.toString();
} catch (SQLException e) {
return e.getMessage()+" ERROR CODE: "+e.getErrorCode();
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
dbConnection = null;
}
}
}
If I delete this line then I didn't got this error:
last_inserted_id = rs.getInt(1);
But after googleing it seems to be ok with this code, which should return me last inserted row id.
Table Description:
CREATE TABLE MEETINGS (
MEETING_ID NUMBER GENERATED ALWAYS AS IDENTITY,
ORGANIZER_EMAIL VARCHAR2(100),
SUBJECT VARCHAR2(250),
START_DATE_TIME TIMESTAMP,
END_DATE_TIME TIMESTAMP,
ATTENDEES_LIST_CONFIDENTIAL CHAR(1),
ATTENDEES_CONF_CONFIDENTIAL CHAR(1),
ATTENDEES_COUNT_INTERNAL NUMBER(11),
ATTENDEES_COUNT_EXTERNAL NUMBER(11),
CONFIRMED_COUNT_INTERNAL NUMBER(11),
CONFIRMED_COUNT_EXTERNAL NUMBER(11),
PREVIOUS_MEETING_ID NUMBER(20),
APPOINTMENT_SOURCE CHAR(1),
MEETING_LOCATION VARCHAR(100),
LATITUDE FLOAT(10),
LONGITUDE FLOAT(10),
MEETING_DESCRIPTION VARCHAR2(1000),
PRIMARY KEY(MEETING_ID)
);
See Question&Answers more detail:
os