Reputation: 383
I can insert into MySQL via Connector/J. But:
res = stmt.executeUpdate(query);
returns nothing. How do I know the new generated row auto increment key value. I need to have reference to row I just generated.
Upvotes: 0
Views: 423
Reputation:
You can either use last_insert_id()
or the the JDBC API to retrieve the generated keys:
String query = "insert into ....";
PreparedStatement pstmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
int rowsAffected = pstmt.executeUpdate();
int newId = -1;
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next())
{
newId = rs.getInt(1);
}
rs.close();
pstmt.close();
Upvotes: 3
Reputation: 1900
the executeUpdate
returns the number of affected rows by your query.
to get the latest auto increment id you will need to execute another query. I have used SELECT LAST_INSERT_ID();
which should return the latest value
Upvotes: 0
Reputation: 108651
Immediately after your insert, on the same connection, issue this SQL query:
SELECT LAST_INSERT_ID()
It returns the most recently generated autoincrement value. It's stored on a per-connection basis, so it's reliable even on a busy multiclient database.
Upvotes: 0