关于“bit”数据类型的问题

时间:2011-07-11 12:08:28

标签: c# asp.net sql

    public static bool CheckIfUserISbanned(Guid guid)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("SELECT Banned");
    sb.Append(" FROM dbo.Users");
    sb.Append(" WHERE UsersID=@UserID");
    object o;
    bool isBanned = false;
    string myConnectionString = AllQuestionsPresented.connectionString;
    using (SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString))
    {
        SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
        conn.Open();
        cmd.Parameters.Add("@UserID", SqlDbType.UniqueIdentifier).Value = guid;
        o = cmd.ExecuteScalar();
    }

    isBanned = o == null ? false : true;//Problem here
    return isBanned;
}

问题是对象总是收到一个非null的值。但是在Banned字段的Users表中,我将其类型设置为“Allow Nulls”...我可以看到有空值,但是没有null被重新读取。还有其他的...这使得“isBanned”参数成为真的...整个时间..为什么会发生这种情况,怎么知道对象什么时候是bool True。

3 个答案:

答案 0 :(得分:6)

如果数据库查询在SQL中返回NULL,则会在.NET中将其转换为DBNull。因此,不要测试null,而是测试DBNull.Value

答案 1 :(得分:1)

您应该在表达式中测试DBNull.Value

答案 2 :(得分:-1)

试试这个:

isBanned = o == null ? false : true;

使用string.Empty

检查字符串是否为空
isBanned = o == string.Empty ? false : true;