Java get id of inserted record in database
To get the ID of an inserted record in a database, you can use the Statement.getGeneratedKeys()
or PreparedStatement.getGeneratedKeys()
method. Here's an example:
String query = "INSERT INTO my_table (col1, col2) VALUES (?, ?)"; PreparedStatement statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); statement.setString(1, "value1"); statement.setString(2, "value2"); int affectedRows = statement.executeUpdate(); if (affectedRows == 0) { throw new SQLException("Inserting data failed, no rows affected."); } ResultSet generatedKeys = statement.getGeneratedKeys(); if (generatedKeys.next()) { long id = generatedKeys.getLong(1); System.out.println("Inserted record ID: " + id); } else { throw new SQLException("Inserting data failed, no ID obtained."); }So:ecruwww.theitroad.com
In this example, we are using a PreparedStatement
to insert a new record into a table. We are setting the values of two columns using setString()
. We are also passing Statement.RETURN_GENERATED_KEYS
to the prepareStatement()
method to indicate that we want to retrieve the generated keys.
After executing the update using executeUpdate()
, we check if any rows were affected. If there were, we retrieve the generated keys using getGeneratedKeys()
. We then check if the result set contains any rows, and if so, we retrieve the value of the first column (which should be the ID of the inserted record).
Note that the specific way to retrieve the generated keys may vary depending on the database you are using. Some databases may require you to use a different method or specify additional options when creating the statement or connection.