What is the most efficient way to check an ExecuteScalar result for existence?

≯℡__Kan透↙ 提交于 2019-12-13 08:04:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!