【发布时间】:2011-03-06 11:52:51
【问题描述】:
我想获取表中最后一个 ID 插入的值。我该怎么做?
【问题讨论】:
我想获取表中最后一个 ID 插入的值。我该怎么做?
【问题讨论】:
我使用的解决方案是:
select id from NEW TABLE (insert into (val1, val2, ...) values ('lorem', 'ipsum', ...))
这会从插入数据库的最后一行获取 id 列:)
【讨论】:
SELECT EMPNO, HIRETYPE, HIREDATE FROM FINAL TABLE ( INSERT INTO EMPSAMP (NAME, SALARY, DEPTNO, LEVEL) VALUES('Mary Smith', 35000.00, 11, 'Associate'))
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()
更新:不要忘记使用以下标志创建preparedStatement Statement.RETURN_GENERATED_KEYS 否则它将不起作用)))
【讨论】:
看看这个答案。
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;
}
或者这个
http://www.php.net/manual/en/function.db2-last-insert-id.php#98361
【讨论】:
SELECT IDENTITY_VAL_LOCAL() AS VAL FROM SYSIBM.SYSDUMMY1
见docs。
【讨论】: