What does this code mean? (C # using mysql)

Can someone give a good explanation for this code:

bool res = (Convert.ToInt32(cmd.ExecuteScalar()) > 0 ? true : false);
+3
source share
5 answers

Separation:

bool res;
int scalarResult = Convert.ToInt32(cmd.ExecuteScalar());
if(scalarResult > 0)
  res = true;
else
  res = false;

Oliver’s suggestion would be better:

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

If the statement being executed returns something greater than zero, set the variable (possibly _res_ult) to true.

: - ExecuteScalar , (ExecuteNonQuery would, ), . , , "SELECT COUNT (*) FROM someTable WHERE someCondition" - .

+2

1- , 1- , res true, false.

ExecuteScalar . , SELECT ID, Name FROM Table; ExecuteScalar, . ExecuteScalar MySQL.

+2

. , . :

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

:

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

If the query results are greater than 0, set res to true, otherwise res is false. The above code example is redundant and can be rewritten as:

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

I sometimes use code like this to check if any rows were affected when running a request to insert, update, or delete. Something like that:

public bool MyInsertMethod(){
    //database code here
    return cmd.ExecuteNonQuery() > 0;
}
+1
source

refer to C #, if still abbreviated .

You may also be interested in such designs:

int a = b ?? 0; 

What does it mean

if (b!=null)
a= b;
else 
a = 0;
+1
source

Source: https://habr.com/ru/post/1744765/


All Articles