rtuner
rtuner

Reputation: 2410

Why does ExecuteNonQuery return 1 even if nothing was updated?

I have a query like:

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

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

Upvotes: 4

Views: 1671

Answers (3)

s4ndhyac
s4ndhyac

Reputation: 586

You should use the connection string option 'use affected rows'. When set to true it will report changed rows instead of found rows.

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

Upvotes: 1

Microsoft DN
Microsoft DN

Reputation: 10030

The return value of ExecuteNonQuery() on an UPDATE query is the number of rows matched by the where clause of the update statement and NOT the number of rows actually updated. So it does make sense..

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

Upvotes: 5

Mike Perrenoud
Mike Perrenoud

Reputation: 67948

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

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

If you were to run that query and the value of Unread was already 'N' then it would return 0 rows.

Upvotes: 7

Related Questions