Saturday, 23 April 2016

How to get ID of inserted record in database ?


Some database operations, especially those involving parent-child relationships (one-to-many), you may want to insert a record into the parent table first, then into the child table. 
But the records in the child table must have a foreign key that refers to the parent table’s primary key.

In such case, you need a technique that retrieves the value of the primary key of the last record inserted (in case, when ID is auto-incremented by the database engine).

For MySQL and Java Derby database
String sql = "YOUR INSERT STATEMENT HERE";
PreparedStatement ps = 
      conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.execute();
ResultSet rs = ps.getGeneratedKeys();
int generatedKey = 0;
if (rs.next()) {
  generatedKey = rs.getInt(1);
}
System.out.println("Inserted record's ID: " + generatedKey); 


For Oracle database
PreparedStatement statement = 
      conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
statement.execute();
PreparedStatement ps = connection.prepareStatement(
            "select your_table_id_sequence.currval from dual");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
  generatedKey = (int) rs.getLong(1);
}
System.out.println("Inserted record's ID: " + generatedKey);


Note : For Oracle database, you should create a sequence for the table’s primary key.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.