Command.ExecuteNonQuery() return always -1

后端 未结 4 1515
一生所求
一生所求 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 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.

提交回复
热议问题