tags:

views:

290

answers:

5

Can anyone give a good explanation of this code:

bool res = (Convert.ToInt32(cmd.ExecuteScalar()) > 0 ? true : false);
+3  A: 

Separated out:

bool res;
int scalarResult = Convert.ToInt32(cmd.ExecuteScalar());
if(scalarResult > 0)
  res = true;
else
  res = false;
David Neale
Erm, that's wrong - ExcuteScalar expects to run a query that returns a single value, so its not "affectedRows" its "queryResult"
Murph
DbCommand.ExecuteScalar is supposed to return the value of the first column of the first record of a recordset. So ExecuteScalar shouldn't return the number of affected rowshttp://msdn.microsoft.com/en-us/library/system.data.common.dbcommand.executescalar.aspx
Thomas
ExecuteScalar does not return affectedRows, it returns first column of first row.
Salman A
Ah, sorry about that. Have amended answer.
David Neale
+1  A: 

If the statement executed returns something larger than zero, than set the variable (probably the _res_ult) to true.

Update: My initial example was wrong - ExecuteScalar doesn't give you the number of affected rows as commenters corrected above (ExecuteNonQuery would, I mixed them up) but returns instead the first column of the first row of the result set. It's usually used for queries that just return a single value anyway, think "SELECT COUNT(*) FROM someTable WHERE someCondition" or something similar.

Benjamin Podszun
+2  A: 

If query result's 1st row, 1st column's integer value is greater than zero res is true otherwise is false.

ExecuteScalar returns only one cell. For example if SELECT ID, Name FROM Table; query is used with ExecuteScalar then only first ID of the result-set is returned. Also ExecuteScalar is not only for MySQL.

HasanGursoy
A: 

Execute scalar returns the first row first column of the results set. It is used frequently when there is only one cell to return. An example would be:

Select count(*) from customers where state = 'NY'

This Expression would then evaluate to:

bool res = (Convert.ToInt32(cmd.ExecuteScalar()) > 0 ? true : false);

If the results from the query are greater than 0 set res equal to true otherwise set res equal to false. The code example posted is redundant and can be re-written as:

bool res = Convert.ToInt32(cmd.ExecuteScalar()) > 0;

I will sometimes use code like this to test whether any rows were affected when an insert, update or delete query was run. Something like this:

public bool MyInsertMethod(){
    //database code here
    return cmd.ExecuteNonQuery() > 0;
}
Jon
A: 

Hi, please refer to C# if else shorthand .

You may also be intrested in such construction:

int a = b ?? 0; 

Which means

if (b!=null)
a= b;
else 
a = 0;
portland