我收到一个未设置为对象实例的" Object引用"我的代码中出错。我相信我理解为什么会这样,但我不知道如何绕过它。这是我的代码:
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查询没有返回任何内容时才会发生这种情况。此方法多次运行,并且第一次运行时它正确运行,因为它返回一个项目。但第二次,因为它没有要返回的项目,它会抛出我提到的错误。
我该如何解决这个问题?
答案 0 :(得分:4)
你可以这样使用
var data= cmd.ExecuteScalar();
if(data!=null)
postDate =data.ToString();
详细
答案 1 :(得分:0)
这将解决您的问题...将postDate = cmd.ExecuteScalar().ToString();
替换为
object postdate = cmd.ExecuteScalar();
if (postdate != null)
{
string getUserName = postdate.ToString();
}