c# - ExecuteReader.HasRows 与 ExecuteScalar() 是 DBNull

标签 c# sql

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

这是通过对照 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/

相关文章:

c# - 当接收对象是 C# COM 对象并且函数具有接口(interface)作为参数时,VBScript 抛出异常

c# - 如何将多个线程同步到一个公共(public)点

c# - Entity Framework 尝试在对象为空时再次延迟加载对象

sql - 链接两个数据库表

mysql - 是否可以使用 mysql 运行 unix 命令

c# - SQL : Select Distinct rows by all columns but omit one column (say ID column)

c# - lambda func 异常,这可能是 .Net Framework 的错误?

mysql - 何时在 MySQL 中使用单引号、双引号和反引号

mysql - 数据库设计。一对多还是多对多?

sql - 检查谁在 MS SQL Server 的表中执行了插入