【问题标题】:"Object reference not set to an instance of an object" gets thrown when no data is returned没有数据返回时抛出“对象引用未设置为对象的实例”
【发布时间】:2013-01-02 16:10:02
【问题描述】:

我在我的代码中收到“对象引用未设置为对象的实例”错误。我相信我理解为什么会发生这种情况,但我不知道如何解决它。这是我的代码:

public string GetLastPost(int subCatId)
{
    SqlConnection conn = null;
    string postDate = null;
    try
    {
        conn = new SqlConnection();
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        conn.Open();

        SqlCommand cmd = new SqlCommand();

        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "forum_GetLastPostDate";
        cmd.Parameters.Add("@SubCategoryId" , subCatId);
        postDate = cmd.ExecuteScalar().ToString();
    } 

这是我的 SQL 查询:

SELECT TOP 1 PostDate
FROM forum_posts
WHERE forum_posts.SubcategoryId = @SubCategoryId
ORDER BY PostId desc

此行抛出错误:

postDate = cmd.ExecuteScalar().ToString();

在调试时我注意到只有当 SQL 查询什么都不返回时才会发生这种情况。此方法多次运行,第一次运行时正确运行,因为它返回一个项目。但是第二次,因为没有要返回的项目,所以抛出了我提到的错误。

我该如何解决这个问题?

【问题讨论】:

标签: asp.net sql-server ado.net sql-server-2008-r2 webforms


【解决方案1】:

你可以这样使用

   var data= cmd.ExecuteScalar();
   if(data!=null)
         postDate =data.ToString();

详情

ExecuteScalar throws NullReferenceException

【讨论】:

    【解决方案2】:

    这将解决您的问题...将postDate = cmd.ExecuteScalar().ToString(); 替换为

    object postdate = cmd.ExecuteScalar();
    if (postdate != null)
    {
    string getUserName = postdate.ToString();
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 2013-11-17
      • 1970-01-01
      相关资源
      最近更新 更多