MrPencil
MrPencil

Reputation: 964

GET the id of the inserted record

I am trying to get the id of the inserted record with the use of getGeneratedKeys. I dont know how to call setId(generatedKeys.getLong(1)); here to get the id? How can I get it to work.

I appreciate any help.

Code:

ResultSet routesTables = dbm.getTables(null, null, "routes",
                        null);
                int route_id;
                if (routesTables.next()) {

                    PreparedStatement prepRoutesInsert = con
                            .prepareStatement("INSERT INTO routes(direction, route)"
                                    + "VALUES( ?, ?)");

                    prepRoutesInsert.setString(1, direction);
                    prepRoutesInsert.setInt(2, route);

                  prepRoutesInsert.executeUpdate();

                     try (ResultSet generatedKeys = prepRoutesInsert.getGeneratedKeys()) {
                         if (generatedKeys.next()) {
                             setId(generatedKeys.getLong(1));
                            }

                     }
}

Upvotes: 1

Views: 59

Answers (1)

MaxZoom
MaxZoom

Reputation: 7743

Generated key is created automatically in the DataBase so there is no need for you to set it.
You can obtain it from the Result Set

int id = generatedKeys.getInt(FIELD_INDEX);

Upvotes: 1

Related Questions