Java, PreparedStatement, TransactSQL (MS SQL), last insert 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";
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...
精彩评论