Command.ExecuteNonQuery() return always -1

2020-04-17 07:40发布

问题:

I have a problem when I executed Select command in C# using ExecuteNonQuery() method; It always return -1; This means that no record returned by the selected statement, doesn't it?

But when i open sql managment studio and run the same select statement; I found that it returned rows.

Please help me!

回答1:

You shouldn't execute a SELECT with an ExecuteNonQuery(). It is called ExecuteNonQuery because you want something to execute that is not a query. A SELECT is a query. You want to ExecuteReader. If you want to do an UPDATE or DELETE, then you can do an ExecuteNonQuery() and that will show how many rows were affected.



回答2:

No, that indicates that it affected no rows.

From the docs for SqlCommand.ExecuteNonQuery (emphasis mine):

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

Perhaps you're looking for ExecuteScalar instead? That's appropriate for - say - fetching a count. It returns a single value from the query. Otherwise (if you want actual results), use ExecuteReader to fetch "normal" results.

A SELECT statement is a query in SQL, so it's really unclear why you'd try to execute one with ExecuteNonQuery.



回答3:

ExecuteNonQuery() is used when you are performing nonquery operations like insert, update or delete, it can't be used for query operation like select. In order to fetch records from DB, use SqlDataReader or SqlDataAdapter but SqlDataReader gives better performance. Have a look at this link describing SqlDataReader.



回答4:

Use ExecuteReader() OR SqlDataAdapter() for fetching rows.



标签: c# asp.net