Java、PreparedStatement、TransactSQL (MS SQL)、最后插入 ID

发布于 2024-10-05 22:53:02 字数 532 浏览 0 评论 0原文

我使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一身骄傲 2024-10-12 22:53:02

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

A PreparedStatement's executeUpdate method DOES indeed return the number of affected rows...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文