My current method is this:
SELECT TOP 1 ID FROM DATAENTRY ORDER BY ID DESC
This assumes the latest inserted item always has the highest unique ID (primary key, autoincrementing). Something smells wrong here.
Alternatives?
My current method is this:
SELECT TOP 1 ID FROM DATAENTRY ORDER BY ID DESC
This assumes the latest inserted item always has the highest unique ID (primary key, autoincrementing). Something smells wrong here.
Alternatives?
If the JDBC driver supports it, you can also just use Statement#getGeneratedKeys()
for that.
String sql = "INSERT INTO tbl (col) VALUES (?)";
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, col);
preparedStatement.executeUpdate();
generatedKeys = preparedStatement.getGeneratedKeys();
if (generatedKeys.next()) {
long id = generatedKeys.getLong(1);
} else {
// Throw exception?
}
IDENTITY()
"under the hoods", but now in a more abstract and DB-agnostic way using pure JDBC API. You have less maintenance headache whenever you'd like to switch of database. If you did it all the right and standard-SQL way, then all you basically need to do is to replace JDBC driver and URL/login. You can keep the coding intact. –
Numbskull If using MySQL you can do
select last_insert_id();
If using MS SQL
select scope_identity();
For H2, I believe it's
CALL SCOPE_IDENTITY();
but I don't have any experience with that DB
SCOPE_IDENTITY()
won't work as expected. See groups.google.com/d/msg/h2-database/0xJsP993RHY/0LERpBvtLNUJ –
Hoodoo SELECT SCOPE_IDENTITY();
instead of SET
. That's all. –
Washko SCOPE_IDENTITY()
is onlz supported in MSSQL mode. –
Deme © 2022 - 2024 — McMap. All rights reserved.