Command.ExecuteNonQuery() return always -1

后端 未结 4 1506
一生所求
一生所求 2021-01-25 04:35

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

相关标签:
4条回答
  • 2021-01-25 04:50

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

    0 讨论(0)
  • 2021-01-25 04:59

    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.

    0 讨论(0)
  • 2021-01-25 05:02

    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.

    0 讨论(0)
  • 2021-01-25 05:12

    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.

    0 讨论(0)
提交回复
热议问题