当没有找到结果时,处理ExecuteScalar返回null

时间:2013-11-30 02:05:13

标签: c# sql sql-server

我有这个代码可能返回没有找到结果 - 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 个答案:

答案 0 :(得分:5)

试试这个:

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

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

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

答案 1 :(得分:2)

您的ExecuteScalar()正在返回DBNull。在使用ExecuteScalar的任何地方,您都会遇到此问题,因此您应该考虑使用SO User Rein's已在相关问题here中编写的下面的通用帮助函数。

这样做:

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;
    }
}

答案 2 :(得分:1)

result = sqlcom.ExecuteScalar() !=null ?  sqlcom.ExecuteScalar().ToString() : string.Empty;
相关问题