How do I get the auto generated id after I insert a new row into a table? Currently I'm doing this but does not work:
String query = "INSERT INTO user (firstname, lastname) VALUES (?,?)";
PreparedStatement pstatement = null;
try {
pstatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
pstatement.setString(1, firstname);
pstatement.setString(2, lastname);
pstatement.executeUpdate();
ResultSet result = pstatement.getGeneratedKeys();
int userId = 0;
if (result.next()) {
userId = result.getInt("id");
}
} catch (SQLException e) {
throw new SQLException(e);
} finally {
pstatement.close();
}
It gives me the following error: Column 'id' not found, but the table 'user' has the column 'id', which is auto incremented.
resultSet.getLong(1)instead of the column name. - f1sh