[英]Get the latest inserted value for an identity primary key
我有一个Statement
,在其中向数据库中的表中插入一些值,该表具有一个主键,该主键的标识为: numBon
。
执行插入命令时,我想获取numBon
的值。
现在,我正在使用此代码:
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("SELECT MAX(numBon) FROM BonInterne");
int numBon;
if (result.next()) {
numBon = result.getInt("numBon");
}
还有其他办法吗?
这是一个自动增量列吗? 假设是,您可以执行以下操作:
SELECT LAST_INSERT_ID()
但这不是数据库不可知的。 本文给出了一个更好的答案。 或者,您可以查看@eidsonator的注释,以更快地获取如何从insert语句获取ID的代码段。
使用Statement.getGeneratedKeys()检索自动生成的值。
Statement st = connection.createStatement();
st.execute("insert into ... "); //query where the server generates a value for
//an auto incremented column
ResultSet rs = st.getGeneratedKeys
int numBon;
if (rs.next()) {
numBon = result.getInt(1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.