当没有结果时,执行ExecuteScalar返回null

4

我有一段代码可能会返回“未找到结果-null”

 String result
 string searchUby = "SELECT text FROM rooms WHERE year=@year AND event=@eventAND text=@text AND z is NULL";
                SqlCommand sqlcom = new SqlCommand(searchUby, conn);
                sqlcom.Parameters.AddWithValue("@event",event.Text);
                sqlcom.Parameters.AddWithValue("@text", cb_room.SelectedItem);
                sqlcom.Parameters.AddWithValue("@year",klientClass.Year());
                conn.Open();                  
                result = sqlcom.ExecuteScalar().ToString(); // on this line ex occurs

                conn.Close();

我得到了这个异常:
NullReferenceException: Object reference not set to an instance of an object. 

有人能帮我解决这个问题吗?

3个回答

6

试试这个:

result = (sqlcom.ExecuteScalar() ?? "").ToString();

如果返回值为null,结果将为空字符串。您可以通过if语句来处理这种情况,并向用户发送一些消息,例如:

object r = sqlcom.ExecuteScalar();  
if(r != null) result = r.ToString();
else {
  //code to handle the null case here...
}

2
你的ExecuteScalar()返回了一个DBNull。你在使用ExecuteScalar时会遇到这个问题,所以你应该考虑使用下面这个通用助手函数,就像SO用户Rein在相关问题这里中写的一样。
只需执行以下操作:
result = ConvertFromDBVal<string>(sqlcom.ExecuteScalar());

使用通用函数:

public static T ConvertFromDBVal<T>(object obj)
{
    if (obj == null || obj == DBNull.Value) {
        return default(T); // returns the default value for the type
    }
    else
    {
        return (T)obj;
    }
}

1
result = sqlcom.ExecuteScalar() !=null ?  sqlcom.ExecuteScalar().ToString() : string.Empty;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接