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
How to get the last insert ID from a table
提问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 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_KEYS
otherwise it won't work)))
更新:并且不要忘记使用以下标志创建preparedStatement,Statement.RETURN_GENERATED_KEYS
否则它将无法工作)))