开发者

Java, PreparedStatement, TransactSQL (MS SQL), last insert id

开发者 https://www.devze.com 2023-01-27 20:12 出处:网络
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 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";

  ResultSe开发者_StackOverflowt rs = stmt.executeQuery(sql);
  int id = 0;
  while (rs.next()) {
   id = rs.getInt("id");
  }
  return id;
 }

Thank you in advance.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消