In general, we call ExecuteNonQuery () when executing SQL statements, and then accept the number of rows affected by declaring an int value, and we can tell whether the SQL statement has been executed by judging the int value. Usually we judge that this int value is greater than 0, because we know that at least the number of rows affected is 1, we judge more than 0 OK, but at run time we find that the value of the statement we judge is false, why? Check out the MSDN documentation at the end and read the explanations.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is-1. If a rollback occurs, the return value is also-1.
When we execute a SELECT statement with ExecuteNonQuery, we have a return value of-1, the rollback occurs in the transaction, and if the execution SQL does not contain a transaction, it can be considered. If there is a transaction, it is necessary to see where the error occurred, causing the commit to be unsuccessful and the transaction to roll back.
Let's take a look at this demo
1 Private intSelect (stringselectquerystring,2 stringconnectionString)3 {4 using(SqlConnection connection =NewSqlConnection (5 connectionString))6 {7SqlCommand Command =NewSqlCommand (selectquerystring, connection);8 command. Connection.Open ();9 intresult=command. ExecuteNonQuery ();Ten returnresult; One } A } - //the value of result is-1 - Private intCommon (stringqueryString, the stringconnectionString) - { - using(SqlConnection connection =NewSqlConnection ( - connectionString)) + { -SqlCommand Command =NewSqlCommand (queryString, connection); + command. Connection.Open (); A intresult=command. ExecuteNonQuery (); at returnresult; - } - } - //The querystring here is the update Insert DELETE statement - //The value of result is the number of rows affected
SqlCommand.ExecuteNonQuery the number of rows affected why would it be-1?