简体   繁体   中英

Retrieve data from database - how?

In my database table I have two columns: pagename and pageinfo . I want to retrieve data when I pass in pagename . I use code which I got from Stackoverflow today but some issue in code throws an error:

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.)

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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