连接没有关闭。连接的当前状态是开放的。 C#错误

时间:2016-07-15 03:46:06

标签: c# .net sql-server

从gridview中保存2个或更多值时出现此错误:

  

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

但是这个过程会经历并保存和更新数据。如何删除此错误?

这是我的代码:

for(int i = 0; i < gvModal.Rows.Count; i++)
{ 
    string dateA = DateTime.Now.ToString("yyyy-MM-dd");

    Utility u = new Utility();
    string conn = u.connect();

    Label type = (Label)gvModal.Rows[i].Cells[1].FindControl("lbltype");
    Label model = (Label)gvModal.Rows[i].Cells[2].FindControl("lblModel");
    Label quantity = (Label)gvModal.Rows[i].Cells[3].FindControl("lblQuan");
    Label unit = (Label)gvModal.Rows[i].Cells[4].FindControl("lblUnit");
    int bal = Convert.ToInt32(gvModal.Rows[i].Cells[4].Text);
    int forIssue = 0;
    int forPO = 0;

    if (bal != 0)
    {
        forIssue = 1;
        forPO = 0;
    }
    else
    {
        forIssue = 0;
        forPO = 1;
    }

    SqlConnection connUser = new SqlConnection(conn);
    SqlCommand read = connUser.CreateCommand();

    string query = "INSERT INTO Mosef_Alert values (@Mosef_No, @Branch, @BU, @Dept, @Section, @Requisitioner, @Accepted, @Date_Accepted, @Reason, @MOSEF_Date, @type, @model, @quantity, @unit)";

    connUser.Open();
    read.CommandText = query;

    read.Parameters.Add(new SqlParameter("@Mosef_No", transIDs));
    read.Parameters.Add(new SqlParameter("@Branch", branch));
    read.Parameters.Add(new SqlParameter("@BU", bu));
    read.Parameters.Add(new SqlParameter("@Dept", dept));
    read.Parameters.Add(new SqlParameter("@Section", sec));
    read.Parameters.Add(new SqlParameter("@Requisitioner", requisitioner));
    read.Parameters.Add(new SqlParameter("@Accepted", accept));
    read.Parameters.Add(new SqlParameter("@Date_Accepted", dateA));
    read.Parameters.Add(new SqlParameter("@Reason", reason));
    read.Parameters.Add(new SqlParameter("@MOSEF_Date", lblDateFiled.Text));
    read.Parameters.Add(new SqlParameter("@type", type.Text));
    read.Parameters.Add(new SqlParameter("@model", model.Text));
    read.Parameters.Add(new SqlParameter("@quantity", quantity.Text));
    read.Parameters.Add(new SqlParameter("@unit", unit.Text));
    read.Parameters.Add(new SqlParameter("@For_PO", forPO));
    read.Parameters.Add(new SqlParameter("@For_Issuance", forIssue));

    read.ExecuteNonQuery();

    read.Parameters.Clear();
}

ExecuteUpdate(accept);
UpdateStatus();

System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"<script type ='text/javascript'>");
sb.Append("alert('Records Updated');");
sb.Append("$('#editModal').modal('hide');");
sb.Append(@"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditHideModalScript", sb.ToString(), false);
}

public void UpdateStatus()
{
        Utility u = new Utility();
        string conn = u.connect();
        SqlConnection connUser = new SqlConnection(conn);
        SqlCommand read = connUser.CreateCommand();

        for(int i = 0; i < gvModal.Rows.Count; i++)
        {
            Label ItemID = (Label)gvModal.Rows[i].Cells[1].FindControl("lblID");
            Label stat = (Label)gvModal.Rows[i].Cells[8].FindControl("ItemStatus");
            int balance = Convert.ToInt32(gvModal.Rows[i].Cells[4].Text);
            string status;

            if(balance != 0)
            {
                status = "For Issuance";
            }
            else
            {
                status = "For PO";
            }

            string upd = "UPDATE ItemTransaction SET ItemStatus = '" + status +"' WHERE ID = '"+ ItemID.Text +"'";

            connUser.Open();
            read.CommandText = upd;

            read.Parameters.Clear();
            read.ExecuteNonQuery();
        }
    }
    public void ExecuteUpdate(int stat)
    {
        string upStat = null;
        if (stat == 1)
        {
            upStat = "Accepted";
        }
        else
        {
            upStat = "Denied";
        }
        string id = transID.Text;
        Utility u = new Utility();
        string conn = u.connect();
        SqlConnection connUser = new SqlConnection(conn);
        string up = "UPDATE MosefTransaction SET TransStatus = '"+ upStat +"' WHERE TransactionID = '"+ id +"'";
        connUser.Open();
        SqlCommand cm = new SqlCommand(up, connUser);
        //cm.Parameters.AddWithValue("@ID", id);
        //cm.Parameters.AddWithValue("@TransStatus", upStat);
        cm.Parameters.Clear();
        cm.ExecuteNonQuery();

        connUser.Close();
    }

1 个答案:

答案 0 :(得分:4)

首先要注意的是,您的纯文本查询为SqlInjection打开了一道大门。所以使用参数化查询。现在让我来看看你的代码, 问题在于UpdateStatus方法,其中您在迭代时打开连接并保持不关闭,因此当您尝试在下一次迭代中再次打开连接时,它会抛出错误。您可以通过多种方式避免这种情况:

  1. 使用connUser.Close()
  2. 关闭每次迭代中的连接
  3. 您可以使用ConnectionState枚举来检查打开新连接之前的连接状态。并且仅在状态未打开时打开它。
  4. 可以使用以下代码完成此操作:

    if (connUser.State != ConnectionState.Open)
        connUser.Open();
    

    3。打开Loop外部的Connection,并使用相同的循环。执行查询后清除每次迭代中的参数。

    例如,考虑代码:

    using (SqlConnection connUser = new SqlConnection(conn))
    {
        string upd = "UPDATE ItemTransaction SET ItemStatus = @status WHERE ID = @id";
        connUser.Open();
        SqlCommand commandSQL = connUser.CreateCommand();
        for (int i = 0; i < gvModal.Rows.Count; i++)
        {
            // Get values here using your code
            commandSQL.Parameters.Add("@status", SqlDbType.VarChar).Value = status;
            commandSQL.Parameters.Add("@id", SqlDbType.VarChar).Value = ItemID.Text;
            commandSQL.ExecuteNonQuery();
            commandSQL.Parameters.Clear();                   
        }
    }
    

    注意:最好的选择是第三个,我希望您遵循这个,剩下的知识,这将在其他情况下帮助您;