-1

我看到了这段代码:

object objvalid = cmd.ExecuteScalar();
//made it this far - must not have thrown an exception
retVal = true;

...但我认为其中一个可能会更好:

object objvalid = cmd.ExecuteScalar();
retVal = (null != objvalid);

...

Int32 anybodyThere = (Int32) cmd.ExecuteScalar();
retVal = anybodyThere > 0;
4

2 回答 2

1

我想你回答了你自己的问题。你不能比这更好

object objvalid = cmd.ExecuteScalar();
retVal = (null != objvalid);

但是,从您的评论看来,您真正想要的是知道表上是否存在列名。为此,我建议您考虑使用DbDataAdapter.FillSchemaorDbConnection.GetSchema代替。这两个选项都允许您针对所有列对数据库执行单个查询,而不是为每一列重新查询数据库。

于 2013-03-12T23:16:23.180 回答
1

首先,您的方法在效率方面没有任何(可衡量的)差异,在这种情况下它是无关紧要的。

你想检查什么?

  • 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.

于 2013-03-12T23:23:26.527 回答