Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL java get value assigned to auto increment primary key [duplicate]

Tags:

java

sql

jdbc

I have a primary key auto increment attribute in my table. I want to know the value assigned to it for a row that is inserted using statement.executeUpdate(). How to achieve this in the best possible manner?

like image 249
Rohit Banga Avatar asked May 17 '10 21:05

Rohit Banga


1 Answers

Use Statement#getGeneratedKeys() and Statement#executeUpdate(String, int) (this is a JDBC 3.0 feature, your database has to support JDBC 3.0).

Here's an example that returns a ResultSet with values for auto-generated columns in TABLE1:

Statement stmt = conn.createStatement();
int rows = stmt.executeUpdate("INSERT INTO TABLE1 (C11, C12) VALUES (1,1)", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
like image 69
Pascal Thivent Avatar answered Oct 27 '22 19:10

Pascal Thivent