Can anyone give a good explanation of this code:
bool res = (Convert.ToInt32(cmd.ExecuteScalar()) > 0 ? true : false);
Can anyone give a good explanation of this code:
bool res = (Convert.ToInt32(cmd.ExecuteScalar()) > 0 ? true : false);
Separated out:
bool res;
int scalarResult = Convert.ToInt32(cmd.ExecuteScalar());
if(scalarResult > 0)
res = true;
else
res = false;
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.
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.
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;
}
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;