【发布时间】:2010-11-30 13:55:36
【问题描述】:
我使用 PreparedStatement 将一些值插入到数据库中,但在这种情况下,我似乎无法检索最后一个插入 ID。
我尝试使用与 Statements 相同的语句(如下),但它不起作用。它说,在这种情况下 .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;
}
提前谢谢你。
【问题讨论】:
-
您从不关闭结果集?
-
当您从控制台或任何前端执行此查询时,您会看到什么?
-
感谢您指出这一点。我通常会这样做,我保证:)
-
问题是这个 PreparedStatement 中的查询是有条件的(见下文),当我在 MS SQL 管理器中运行它时,它不会插入任何东西(原样预期)。
-
if ((select COUNT(id) as quantity from tNewSchedule where ManID = 464 and (type & 264) > 0 and status = 0) = 0) BEGIN INSERT INTO tnewschedule (type, to_review, manid , 父) -- 值 (300, '2010-11-30 16:30:16.036', 464, 271);结束
标签: java sql-server lastinsertid