在我网站的某个区域,我需要控制对一组特定用户的访问。
这是通过对照 SQL 服务器数据库上的表检查用户 ID 来完成的。如果 ID 存在,则他们被授予访问权限:
SELECT 1 FROM admin WHERE userID = @userID
我注意到有几种方法可以检查数据库中是否存在一行,我想知道使用其中任何一种方法是否有任何好处,或者是否有标准。
第一种方法是检查 SqlDataReader
中是否存在行:
if (!SqlCommand.ExecuteReader().HasRows)
{
//redirect
}
第二个是使用 ExecuteScalar()
检查返回值是否为 DBNull
:
if (SqlCommand.ExecuteScalar() is DBNull)
{
//redirect
}
我应该使用哪个?有没有更好的办法?这真的重要吗?
最佳答案
第二个选项,因为您的开销较小。
不过请注意
ExecuteScalar返回一个对象是
The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty
您的查询可能不会返回任何内容,因此最好检查 null 而不是 DBNull
if (SqlCommand.ExecuteScalar() == null)
{
//redirect
}
关于c# - ExecuteReader.HasRows 与 ExecuteScalar() 是 DBNull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13527300/