I would like to use sqlite (using Java JDBC, not sure if that matters) to add or replace a new row to a database, and return the autogenerated ID of the row, and I’m not sure how to do this efficiently/cleanly.
table definition has >= 3 columns:
- autogenerated integer
ID - unique key string (let’s call it
key) - other metadata
I can think of two general approaches:
SELECT ID FROM myTable WHERE key = ?- If there’s no match, INSERT a new row, and repeat step #1 to get the autogenerated ID
or
INSERT OR REPLACE INTO myTable (key, metadata) VALUES (?, ?)SELECT ID FROM myTable WHERE key = ?
What should I do? Not sure if either approach is an atomic transaction. (well, the first isn’t, not sure about the 2nd)
edit: I just tried the INSERT OR REPLACE approach, and it “works”, except that it also replaces the ID with a new one, which is not what I want to have happen. I want to keep the existing ID.
Using a PreparedStatement you can return the generated key for an insert so there is no need to run a select statement after a insert just to get the key.
To do this:
the method that allows you specify it
to return the generated keys.