1

我正在尝试以下代码:

SqlConnection con = new SqlConnection();
    con.ConnectionString = Userfunctions.GetConnectionString();
    con.Open();
    for (int i = 0; i < studList.Rows.Count; i++)
    {
        //string a = ((DropDownList)studList.Rows[i].FindControl("actionmenu")).SelectedValue;

            string grade = ((DropDownList)studList.Rows[i].FindControl("actionmenu")).SelectedValue;
            string studentID = studList.Rows[i].Cells[1].Text;
            string courseNumber = MyGlobals.selectedCourse.Substring(MyGlobals.selectedCourse.Length-3);
            string courseCode = MyGlobals.selectedCourse.Substring(0, MyGlobals.selectedCourse.Length - 3);
            SqlCommand com = new SqlCommand("update RegisterTable set Grade=@grade where StudentID=@studentID and CourseCode=@courseCode and CourseNumber=@courseNumber", con);
            com.Parameters.AddWithValue("@grade", grade);
            com.Parameters.AddWithValue("@studentID", studentID);
            com.Parameters.AddWithValue("@courseCode", courseCode);
            com.Parameters.AddWithValue("@courseNumber", courseNumber);
            com.ExecuteNonQuery();

            try
            {
                SqlDataAdapter da2 = new SqlDataAdapter(com);

                DataTable dt2 = new DataTable();
                da2.Fill(dt2);
                DataRow dr2 = dt2.Rows[0];

                Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
                Register reg = new Register(c, MyGlobals.student);

                MyGlobals.student.dropCourse(reg);

            }
            catch (Exception) { }
            con.Close();

即使我打开数据库连接,它也会给出一个错误,提示 ExecuteNonQuery 需要一个打开且可用的连接。连接的当前状态为关闭。为什么有人能看到这种情况?谢谢

4

2 回答 2

2

您正在关闭 for 循环内的连接,因此在第二次迭代中,连接未打开。它应该如下所示:

SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
for (int i = 0; i < studList.Rows.Count; i++)
{
    ...
    SqlCommand com = new SqlCommand(..., con);
    ...
    com.ExecuteNonQuery();

    try
    {
        ...
    }
    catch (Exception) { }
}
con.Close();
于 2013-06-05T19:47:51.927 回答
0

您正在关闭循环中的连接,因此它将继续进行第二次迭代并且连接将被关闭。

于 2013-06-05T19:48:17.340 回答