为什么我在asp.net中遇到数据库的连接错误?

时间:2013-06-05 19:44:18

标签: asp.net database

我正在尝试以下代码:

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需要一个开放且可用的连接。连接的当前状态已关闭。为什么有人能看到这个案子? 感谢

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

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