This doesn't explain why it should be like that, but it explains why it could happen. The following byte-code sets -1
to the internal updateCount
flag in the SQLServerStatement
constructor:
// Method descriptor #401 (Lcom/microsoft/sqlserver/jdbc/SQLServerConnection;II)V
// Stack: 5, Locals: 8
SQLServerStatement(
com.microsoft.sqlserver.jdbc.SQLServerConnection arg0, int arg1, int arg2)
throws com.microsoft.sqlserver.jdbc.SQLServerException;
// [...]
34 aload_0 [this]
35 iconst_m1
36 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]
Now, I will not analyse all possible control-flows, but I'd just say that this is the internal default initialisation value that somehow leaks out to client code. Note, this is also done in other methods:
// Method descriptor #383 ()V
// Stack: 2, Locals: 1
final void resetForReexecute()
throws com.microsoft.sqlserver.jdbc.SQLServerException;
// [...]
10 aload_0 [this]
11 iconst_m1
12 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]
// Method descriptor #383 ()V
// Stack: 3, Locals: 3
final void clearLastResult();
0 aload_0 [this]
1 iconst_m1
2 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]
In other words, you're probably safe interpreting -1
as being the same as 0
. If you rely on this result value, maybe stay on the safe side and do your checks as follows:
// No rows affected
if (stmt.executeUpdate() <= 0) {
}
// Rows affected
else {
}
UPDATE: While reading Mark Rotteveel's answer, I tend to agree with him, assuming that -1
is the JDBC-compliant value for "unknown update counts". Even if this isn't documented on the relevant method's Javadoc, it's documented in the JDBC specs, chapter 13.1.2.3 Returning Unknown or Multiple Results. In this very case, it could be said that an IF .. INSERT ..
statement will have an "unknown update count", as this statement isn't SQL-standard compliant anyway.