Enrique San Martín
Enrique San Martín

Reputation: 2246

How to get the last insert ID from a table

I want to get the value of the last ID insert in a table. How I can do this?

Upvotes: 23

Views: 36277

Answers (4)

Enrique San Martín
Enrique San Martín

Reputation: 2246

Well the solution that I use is:

select id from NEW TABLE (insert into (val1, val2, ...) values ('lorem', 'ipsum', ...))

This gets the id column from the last row inserted in the DB :)

Upvotes: 28

Anatoly
Anatoly

Reputation: 5241

int keyId = -1;
preparedStatement.executeUpdate();
resultSet = preparedStatement.getGeneratedKeys();
if (resultSet.next()) {
    keyId = rs.getInt(1);
}

https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#getGeneratedKeys()

Update: and don't forget to create preparedStatement with the following flag Statement.RETURN_GENERATED_KEYS otherwise it won't work)))

Upvotes: -3

Vibhaj
Vibhaj

Reputation: 189

Have a look at this answer.

http://www.sitepoint.com/php-database-db2/

// get the last inserted ID into the specified table  
// int lastInsertID(string $tblName)  
function lastInsertID($tblName)  
{  
 if ($this->transIsOpen())  
 {  
   $sql = "SELECT SYSIBM.IDENTITY_VAL_LOCAL() AS id FROM " . $tblName;  
   $rs = $this->query($sql);  
   return $this->fetch($rs, "id");  
 }  
 return -1;  
}

OR this

http://www.php.net/manual/en/function.db2-last-insert-id.php#98361

Upvotes: 0

Bill Karwin
Bill Karwin

Reputation: 562621

SELECT IDENTITY_VAL_LOCAL() AS VAL FROM SYSIBM.SYSDUMMY1

See docs.

Upvotes: 16

Related Questions