title: Java, PreparedStatement, TransactSQL (MS SQL), last insert id
body: <p>I insert some values into a database using a PreparedStatement, but it seems, that i cannot retrieve the last insert id in that case. </p>
  
  <p>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.</p>
  
  <p>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. </p>
  
  <p>Here is the method.</p>
  
  <pre><code> 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;
   }
  </code></pre>
  
  <p>Thank you in advance. </p>