问题
I'm seeing this code:
object objvalid = cmd.ExecuteScalar();
//made it this far - must not have thrown an exception
retVal = true;
...but am thinking one of these might be better:
object objvalid = cmd.ExecuteScalar();
retVal = (null != objvalid);
...
Int32 anybodyThere = (Int32) cmd.ExecuteScalar();
retVal = anybodyThere > 0;
回答1:
I think you answered your own question. You can't get much better than this
object objvalid = cmd.ExecuteScalar();
retVal = (null != objvalid);
However, from your comment, it seems like what you really want is to know if a column name exists on a table. For this purpose I suggest you look into using DbDataAdapter.FillSchema or DbConnection.GetSchema instead. Both options allow you to execute a single query against the database for all columns rather than re-querying the database for every column.
回答2:
First, your approaches do not make any (measurable) difference in terms of efficiency, it's just irrelevant in this case.
What do you want to check?
- If it can return
null
and you want to know that, check that. Then your second aproach is the best. - If the query returns a numeric value (e.g. from
COUNT
) and you want to know if it's greater than zero, just check that. Then the last approach is fine.
However, you first approach is not good practise, don't rely on exceptions in your normal flow of control.
来源:https://stackoverflow.com/questions/15374038/what-is-the-most-efficient-way-to-check-an-executescalar-result-for-existence