Yasin
Yasin

Reputation: 2029

Not able to get the newly generated primary key from MySQL database using JDBC

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

Answers (1)

user432
user432

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

Related Questions