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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3087836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 06:38:08  来源:igfitidea点击:

How to get the last insert ID from a table

sqldb2

提问by Enrique San Martín

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

我想获取表中最后一个 ID 插入的值。我怎么能做到这一点?

回答by Enrique San Martín

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 :)

这从插入数据库的最后一行获取 id 列:)

回答by Bill Karwin

SELECT IDENTITY_VAL_LOCAL() AS VAL FROM SYSIBM.SYSDUMMY1

See docs.

请参阅文档

回答by Vibhaj

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

回答by Anatoly

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_KEYSotherwise it won't work)))

更新:并且不要忘记使用以下标志创建preparedStatement,Statement.RETURN_GENERATED_KEYS否则它将无法工作)))