0

According to MSDN article OdbcCommand.ExecuteNonQuery Method

It be defined as below:

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1.

(No support SELECT statments ?)

And this is my sample code in C#.net(my database is PostgreSQL):

odbcCommand.CommandText = "SELECT key_id FROM sometable WHERE p1 = 1";
Console.WriteLine(odbcCommand.ExecuteNonQuery());

It really works. It can return the count of select rows correctly.

But when I search some articles in stackoverflow, ex:( ExecuteNonQuery() ),( ExecuteNonQuery for SELECT sql statement returning no rows ).

They do not recommend use ExecuteNonQuery() to get count of select rows,but recommend use ExecuteReader and loop to get count. (It seems that ExecuteNonQuery() sometimes will get wrong value?)

So,my question is "Can I continue using ExecuteNonQuery() to get count ?(Although it works)"

Community
  • 1
  • 1
Rex Liu
  • 5
  • 1
  • 4
  • you can get the values affcted using executenonquery as it will return thre total number of rows affected. but if you want to work with the specific value of the table that are affected then you need to use count or reader for that – cracker Aug 12 '14 at 06:05
  • Its not recommended because the query sucks. If I ask you how many book you have in a library I do not expect you to go off into the shelves to read the title of each book. I expect you to go to the index and read the answer there. – Aron Aug 12 '14 at 06:05
  • why you want to get that there is no real value if you want data cound you can it after results have been returned – Paritosh Aug 12 '14 at 06:20

2 Answers2

2

You can use it, but the result set is a set of rows.

For better Performance u should use

Select Count(whatever) ....

and than use ExecuteScalar that returns just one value, in this case the result of the Count().

Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

ExecuteScalar on msdn

S.L.
  • 1,056
  • 7
  • 15
0

You may find the underlying driver you are using happens to support this. If you were to switch to a different driver I would not assume the same behaviour.

http://en.wikipedia.org/wiki/ODBC

Because different technologies have different capabilities, most ODBC drivers do not implement all functionality defined in the ODBC standard. Some drivers offer extra functionality not defined by the standard.