Why does ExecuteNonQuery return 1 even if nothing has been updated?

I have a query like:

UPDATE messages SET Unread = 'N' WHERE id= '6' 

To read the affected lines, I use the value ExecuteNonQuery() , but it always returns 1, even if nothing has changed. Saw the same problem here . Is this a mistake or is this behavior normal?

+4
source share
3 answers

For ExecuteNonQuery to return 1 there should be a record WHERE id = '6' . Now, if you want to update the line, if the value is different, change the query:

 UPDATE messages SET Unread = 'N' WHERE id = '6' AND Unread <> 'N' 

If you ran this query and the Unread value Unread already 'N' , then it will return the string 0 .

+7
source

The return value of ExecuteNonQuery() in an UPDATE query is the number of rows matching the where clause of the update and NOT statements, the number of rows actually updated, so that makes sense.

Please view this link and all your doubts will be cleared.

+5
source

You must use the "use affected strings" connection string parameter. When set to true, it will report changed rows instead of found rows.

Refer to https://dev.mysql.com/doc/connector-net/en/connector-net-connection-options.html

+1
source

Source: https://habr.com/ru/post/1492942/


All Articles