错误:未关闭连接。连接的当前状态为打开

时间:2018-12-01 06:56:06

标签: asp.net sql-server

我的连接有问题,我在创建新连接(Payment())之前关闭了所有连接,但它表示存在打开的连接。我还是C#的新手,所以我真的需要您的帮助...

这是我的有问题的代码:

public void Payment()
{
    // start session
    if (Session["User_Email"] != null)
    {
        string GUsername = Session["User_Email"].ToString();
        string ORnum = Session["OR"].ToString();
        int num =Convert.ToInt32(ORnum);

        conn.Open();    // this where error occurs

        query = "SELECT * FROM CartForDelivery where User_Email = '" + GUsername + "' and OR = '" + num + "';";

        SqlCommand cmd = new SqlCommand(query, conn);
        SqlDataReader dreader = cmd.ExecuteReader();

        while (dreader.Read())
        {
            lblpayment.Text = dreader.GetInt32(6).ToString();
        }

        dreader.Close();
        conn.Close();
    }    // end session
}

错误说:

  

连接未关闭。连接的当前状态为打开。

这发生在第conn.Open();

再次感谢! :)

1 个答案:

答案 0 :(得分:1)

     Please always use with in using () command as 
     //conn.Open();
     using(SqlConnection conn = new SqlConnection(connectionstring)){
        conn.Open();
     using(SqlCommand cmd = new SqlCommand(query, conn)){
            SqlDataReader dreader = cmd.ExecuteReader();

            while (dreader.Read())
            {
                lblpayment.Text = dreader.GetInt32(6).ToString();
           }
   }
 }

  It will automatically closes the object