M
M
Max2021-05-04 11:40:29
Java
Max, 2021-05-04 11:40:29

How in java when adding a new record to the SQLite database, return the id (auto-increment) of this particular record?

My multi-user application works with a SQLite database. When creating an object, a record is added to the database, but since the object contains an id field and it is generated by the database, I need to return the id from the database when creating the record in order to assign it to the object on the client, so as not to constantly update all objects from the database. Tell me the right way, so that the database is guaranteed to return the id of this particular record, and not the last one created. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-05-04
@Max_LiVi

In the same Statement or PreparedStatement query, use something like this:

try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
            if (generatedKeys.next()) {
              long id =  generatedKeys.getLong(1);
            }
            else {
                throw new SQLException("No ID obtained");
            }
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question