I\'m working with JDBC and HSQLDB 2.2.9. What\'s the most efficient and accurate way to insert a new row into a DB and, subsequently, retain its id
(PK set to a
I don't have enough reputation to comment on neizan's answer, but here's how I solved the same problem:
Example using HSQLDB 2.2.9:
CREATE TABLE MY_TABLE (
ID INTEGER IDENTITY,
NAME VARCHAR(30)
)
Then in Java:
PreparedStatement result = cnx.prepareStatement(
"INSERT INTO MY_TABLE(ID, NAME) VALUES(NULL, 'TOM');",
RETURN_GENERATED_KEYS);
int updated = result.executeUpdate();
if (updated == 1) {
ResultSet generatedKeys = result.getGeneratedKeys();
if (generatedKeys.next()) {
int key = generatedKeys.getInt(1);
}
}