tags:

views:

52

answers:

1

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?

+3  A: 

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();
Pascal Thivent
i get an error saying column id not found when i call rs.getInt("id");what could be the reason?
iamrohitbanga
something related.http://bugs.mysql.com/bug.php?id=18409but even this does not solve the problem
iamrohitbanga
my column has a datatype of int(11). i am using mysql
iamrohitbanga
@iamrohitbanga Did you try to retrieve the column by index `rs.getInt(1);`?
Pascal Thivent
yes i did. i still get an exception. i have posted a new question here.http://stackoverflow.com/questions/2854774/sql-jdbc-getgeneratedkeys-returns-column-id-not-found-column-type-unknown
iamrohitbanga
i have put up the stack trace as well as the datatypes of the columns in the table. see the link above.
iamrohitbanga
@Pascal any idea
iamrohitbanga