简体   繁体   English

DB2如何从表中获取最后一个插入ID

[英]DB2 how to get the last insert id from a table

i want to get the value of the last id insert in a table. 我想获取表中最后一个id插入的值。 How i can do this? 我怎么能这样做?

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 :) 这从DB中插入的最后一行获取id列:)

SELECT IDENTITY_VAL_LOCAL() AS VAL FROM SYSIBM.SYSDUMMY1

查看文档

Have a look at this answer. 看看这个答案。

http://www.sitepoint.com/php-database-db2/ 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 http://www.php.net/manual/en/function.db2-last-insert-id.php#98361

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() 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))) 更新:并且不要忘记使用以下标志Statement.RETURN_GENERATED_KEYS创建preparedStatement,否则它将无法工作)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM