Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to auto increment identity field after SQL insert in Java

Tags:

java

sql

Any advice on how to read auto-incrementing identity field assigned to newly created record from call through java.sql.Statement.executeUpdate?

I know how to do this in SQL for several DB platforms, but would like to know what database independent interfaces exist in java.sql to do this, and any input on people's experience with this across DB platforms.

like image 739
Sean Avatar asked Sep 16 '08 19:09

Sean


People also ask

How can I get auto increment value after insert?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.

How do I automatically increase ID in SQL?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

How can I change column auto increment in SQL Server?

ALTER TABLE Inventory MODIFY COLUMN item_number INT AUTO_INCREMENT=50; After running this code, future item IDs will start at an item_number of 50 and increment by 1. To change the starting increment value and increment in SQL Server, set your non-default values during table creation.


Video Answer


1 Answers

The following snibblet of code should do ya':

PreparedStatement stmt = conn.prepareStatement(sql, 
                                 Statement.RETURN_GENERATED_KEYS);
// ...

ResultSet res = stmt.getGeneratedKeys();
while (res.next())
    System.out.println("Generated key: " + res.getInt(1));

This is known to work on the following databases

  • Derby
  • MySQL
  • SQL Server

For databases where it doesn't work (HSQLDB, Oracle, PostgreSQL, etc), you will need to futz with database-specific tricks. For example, on PostgreSQL you would make a call to SELECT NEXTVAL(...) for the sequence in question.

Note that the parameters for executeUpdate(...) are analogous.

like image 83
Daniel Spiewak Avatar answered Oct 14 '22 22:10

Daniel Spiewak