Java、PreparedStatement、TransactSQL (MS SQL)、最后插入 ID
我使用PreparedStatement 将一些值插入数据库,但在这种情况下我似乎无法检索最后一个插入ID。
我尝试使用与语句(如下)相同的语句,但它不起作用。它说,在这种情况下 .executeQuery() 不能接受参数。
事实上,我并不完全需要最后一个插入 ID,受影响的行数就可以了,但我如何得到它呢?我认为PreparedStatement的.executeUpdate()方法会返回受影响的行数,但显然它不会。
这是方法。
public static int getLastInsertId(Statement stmt) throws SQLException {
String sql = "SELECT SCOPE_IDENTITY() AS id";
ResultSet rs = stmt.executeQuery(sql);
int id = 0;
while (rs.next()) {
id = rs.getInt("id");
}
return id;
}
先感谢您。
I insert some values into a database using a PreparedStatement, but it seems, that i cannot retrieve the last insert id in that case.
I try to use the same statement as i use for Statements (below) but it doent work. It says, that .executeQuery() cannot take arguments in this case.
In fact, i don't exactly need the last insert id, the number of affected rows will do, but how do i get that? I thought PreparedStatement's .executeUpdate() method would return the number of affected rows, but it apparently it does not.
Here is the method.
public static int getLastInsertId(Statement stmt) throws SQLException {
String sql = "SELECT SCOPE_IDENTITY() AS id";
ResultSet rs = stmt.executeQuery(sql);
int id = 0;
while (rs.next()) {
id = rs.getInt("id");
}
return id;
}
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个PreparedStatement的executeUpdate方法确实返回受影响的行数......
A PreparedStatement's executeUpdate method DOES indeed return the number of affected rows...