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
2010-05-17 21:47:37
i get an error saying column id not found when i call rs.getInt("id");what could be the reason?
iamrohitbanga
2010-05-18 04:56:43
something related.http://bugs.mysql.com/bug.php?id=18409but even this does not solve the problem
iamrohitbanga
2010-05-18 05:17:42
my column has a datatype of int(11). i am using mysql
iamrohitbanga
2010-05-18 05:22:41
@iamrohitbanga Did you try to retrieve the column by index `rs.getInt(1);`?
Pascal Thivent
2010-05-18 08:25:50
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
2010-05-18 09:04:57
i have put up the stack trace as well as the datatypes of the columns in the table. see the link above.
iamrohitbanga
2010-05-18 09:05:32
@Pascal any idea
iamrohitbanga
2010-05-18 10:24:09