ExecuteReader.HasRows vs ExecuteScalar()是DBNull

时间:2012-11-23 10:35:22

标签: c# sql

在我网站的某个区域,我需要控制对特定用户组的访问权限。

这是通过针对SQL Server数据库上的表检查用户的ID来完成的。如果该ID存在,则授予他们访问权限:

SELECT 1 FROM admin WHERE userID = @userID

我注意到有几种方法可以检查数据库中是否存在行,并且想知道使用其中任何一个是否有任何好处,或者是否有标准。

首先是检查SqlDataReader中是否存在行:

if (!SqlCommand.ExecuteReader().HasRows)
{ 
    //redirect 
}

第二种方法是使用DBNull检查返回的值是否为ExecuteScalar()

if (SqlCommand.ExecuteScalar() is DBNull)
{ 
    //redirect 
}

我应该使用哪个?有没有更好的办法?这真的很重要吗?

3 个答案:

答案 0 :(得分:3)

第二种选择,因为你的开销较少 但请注意

ExecuteScalar返回

对象
  

结果集中第一行的第一列,或null   如果结果集为空,则为引用(在Visual Basic中为Nothing)

您的查询可能不会返回任何内容,因此最好检查null而不是DBNull

if (SqlCommand.ExecuteScalar() == null)
{ 
    //redirect 
}

答案 1 :(得分:1)

两者在性能方面都是相同的。

ExecuteScalar仅返回数据集第一行的第一个值。内部它被处理就像ExecuteReader(),一个DataReader打开,值被选中,DataReader后来被销毁。我也总是想知道这个行为,但它有一个好处:它发生在框架内......你不能以速度的方式与框架竞争。

以下是这两者之间的区别:

ExecuteReader():

1.will work with Action and Non-Action Queries (Select)
2.Returns the collection of rows selected by the Query.
3.Return type is DataReader.
4.Return value is compulsory and should be assigned to an another object DataReader.

ExecuteScalar():

1.will work with Non-Action Queries that contain aggregate functions.
2.Return the first row and first column value of the query result.
3.Return type is object.
4.Return value is compulsory and should be assigned to a variable of required type.

取自

http://nareshkamuni.blogspot.in/2012/05/what-is-difference-between.html

答案 2 :(得分:0)

在你的情况下,它不会影响很多性能,所以你可以使用它们。

  • 当您的查询返回单个值时,通常会使用ExecuteScalar。如果它返回更多,则结果是第一行的第一列。一个例子可能是SELECT @@IDENTITY AS 'Identity'.
  • ExecuteReader用于任何具有多行/列的结果集(例如,SELECT col1,来自sometable的col2)。

SOURCE