2

I am inserting records into a database table through plain old JDBC(as this is what the set up is in the project I am working on.. not yet migrated to Hibernate).

here is my table structure

employee (empid int indentity not null, empName);

when I try to insert record through JDBC code

insert into employee(empName) values('something')

it works and a record gets inserted. However I need to get the id against the inserted row. I can try executing a separate select query to get the inserted row but might not get the correct inserted record id if 2 employee names are same.

How do I get the inserted record id using JDBC. I am using preparedStatment.executeUpdate which returns 0 or 1 based on whether the record is inserted or not.

user3137375
  • 113
  • 1
  • 5

3 Answers3

2

Per the the Statement JavaDoc, you can use "RETURN_GENERATED_KEYS" like so -

stmt.execute("insert into employee(empName) values('something')",
    Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
  return rs.getLong(1); // for example.
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

You want to read the documentation for JDBC's Statement#getGeneratedKeys(), which you must call after doing the insert. This assumes your database supports retrieving generated keys, which not all databases do.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
0

It depends from the db:

Oracle & PostgreSQL: when you use a sequence, get the value returned

Mysql: mysql_insert_id()

SQL Server: @@IDENTITY

Custom way: select max(id) from table

Pure java (JDBC Driver supported): see Statement.getGeneratedKeys() Retrieves any auto-generated keys created as a result of executing this Statement object.

venergiac
  • 7,469
  • 2
  • 48
  • 70