【问题标题】:Java, PreparedStatement, TransactSQL (MS SQL), last insert idJava、PreparedStatement、TransactSQL (MS SQL)、最后插入 ID
【发布时间】: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


【解决方案1】:

PreparedStatement 的 executeUpdate 方法确实返回了受影响的行数...

【讨论】:

  • 显然是这样。我对他们的 javadoc 中的措辞有点失望,而且我有点混淆了我的preparedstatement 的参数(它们很多)。谢谢,对我的错误深表歉意。
猜你喜欢
  • 2011-07-27
  • 2017-09-03
  • 2011-05-24
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多