Reputation: 2029
I am using Statement.RETURN_GENERATED_KEYS
flag to obtan the newly generated primary key value after every insert in the database.
Here is the code snippet:
Connection conn = null;
conn = getDBConnection(); //Susseccfully returns a proper Connection object
PreparedStatement stmt = null;
String sql = "INSERT INTO ..."; //Proper error free INSERT query
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//to obtain the new primary key
i = stmt.executeUpdate();//the value of i is always 1 :(
Not able to understand why this is happening. My driver is com.mysql.jdbc.Driver
EDIT: The primary key's data tyoe is BIGINT
in the DB and its the second column in the table.
Upvotes: 0
Views: 244
Reputation: 3534
executeUpdate()
returns the number of affected rows.
Call stmt.getGeneratedKeys()
to get a ResultSet
with the generated keys:
long key = -1L;
PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//to obtain the new primary key
// execute statement
int affectedRows = stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
// get generated key
if (rs != null && rs.next()) {
key = rs.getLong(1);
}
Upvotes: 2