0

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.

Yasin
  • 1,906
  • 1
  • 21
  • 37

1 Answers1

2

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);
}
user432
  • 3,506
  • 17
  • 24
  • 1
    What is 1 in `getInt(1)`? – Yasin Jun 04 '14 at 11:55
  • 1
    OK so its not `rs.getInt(1)` but `rs.getLong(1)`. I think this is because the data type of the primary key is BigInt. But still I am not getting why 1? – Yasin Jun 04 '14 at 12:05
  • 2
    @user3619962 It is a `ResultSet` object which just consists of 1 column with the generated keys. With `rs.getLong(1);` you get the value of the first column that contains the generated key. – user432 Jun 04 '14 at 12:13