简体   繁体   English

从数据库检索数据-如何?

[英]Retrieve data from database - how?

In my database table I have two columns: pagename and pageinfo . 在数据库表中,我有两列: pagenamepageinfo I want to retrieve data when I pass in pagename . 我希望在传递pagename时检索数据。 I use code which I got from Stackoverflow today but some issue in code throws an error: 我使用了今天从Stackoverflow获得的代码,但是代码中的某些问题引发了错误:

An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code.Additional information: Invalid attempt to read when no data is present.) System.Data.dll中发生类型'System.InvalidOperationException'的异常,但未在用户代码中处理。其他信息:在不存在数据的情况下,尝试读取无效。)

This is the code: 这是代码:

public string GetPageInfo(string filenames)
{
    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=.;Integrated Security=True");

    con.Open();

    SqlCommand command = new SqlCommand("Select pageinfo from T_Pages where pagename=@filenames", con);

    command.Parameters.AddWithValue("@filenames", filenames);

    // int result = command.ExecuteNonQuery();
    using (SqlDataReader reader = command.ExecuteReader())
    {
        return reader["pageinfo"].ToString(); ;
    }

    // return string GetPageInfo;
}

This is because of this: 这是因为:

return reader["pageinfo"].ToString();

if reader["pageinfo"] is null, then ToString() will throw an exception. 如果读取器[“pageinfo”]为空,则的ToString()将抛出异常。

Replace above line with this: 替换上面的行:

if(reader["pageinfo"] != null)
{
   return reader["pageinfo"].ToString();
}
else
{
   return "";
}

Or using Null-conditional Operators : 或使用空条件运算符

return reader["pageinfo"]?.ToString();

EDIT 编辑

You also need to add Read() before return: 您还需要在返回之前添加Read()

reader.Read();
return reader["pageinfo"]?.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM