我正在尝试从数据库中的表中检索值,但不能这样做。
这是我的代码
int crs_Id = Convert.ToInt32(Session["crs_id"]);
SqlDataReader r1, r2, r3;
con.Open();
SqlCommand cmd2 = new SqlCommand("Select Course_Title, Description from COURSE where course_ID='" + crs_Id + "'", con);
r1 = cmd2.ExecuteReader();
Label5.Text = r1["Course_Title"].ToString();
Label6.Text = r1["Description"].ToString();
r1.Close();
SqlCommand cmd3 = new SqlCommand("Select Tutor_ID from Teaching where course_ID='" + crs_Id + "'", con);
r2 = cmd3.ExecuteReader();
if (r2.Read())
{
int tutor = Convert.ToInt32(r2["Tutor_ID"]);
r2.Close();
SqlCommand cmd4 = new SqlCommand("Select Tutor_Name from TUTOR where Tutor_Id='" + tutor + "'", con);
r3 = cmd4.ExecuteReader();
Label7.Text = "Tutor Name is " + r3["Tutor_Name"].ToString() + "";
r3.Close();
}
else
r2.Close();
我正在获取例外情况,如屏幕截图所示
答案 0 :(得分:1)
您收到错误是因为您没有在SqlDataReader
返回的ExecuteReader
中读取第一行。您可以检查r1.HasRows
属性,只有在返回行时才访问列。您还需要执行r1.Read()
以获取第一行。
r1 = cmd2.ExecuteReader();
if ( r1.HasRows )
{
r1.Read();
Label5.Text = r1["Course_Title"].ToString();
Label6.Text = r1["Description"].ToString();
}
else
{
Label5.Text = "";
Label6.Text = "";
}