【问题标题】:How to fix "The connection was not closed, The connection's current state is open."如何修复“连接未关闭,连接的当前状态为打开。”
【发布时间】:2023-01-11 17:58:28
【问题描述】:

每当我点击我网页上的删除按钮时,我总是收到“连接未关闭。连接的当前状态是打开的。”,但是我已经关闭了连接。

 protected void DeleteButton_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand comm = new SqlCommand("DELETE FROM [Table] where [Id] ='"+Id.Text+"'", con);
            comm.ExecuteNonQuery();
            con.Close();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Successfully Deleted');", true);

            disp_data();
        }

我什至试图改变

con.Close(); 

con.Dispose();

但我最终遇到了同样的错误

【问题讨论】:

  • 看起来您正在保持一个连接并将其用于所有目的。不要那样做。在需要时创建新连接,请使用 using 模式。
  • 我觉得在使用 block close 连接自动关闭的时候最好使用using (SqlConnection connection = new SqlConnection(connectionString)) { }
  • 了解如何正确安全地参数化您的 SQL 查询。您的代码对 SQL 注入开放。
  • 您也不应该在同一个类中混合使用 UI 和数据访问。将它们捆绑在一起使得很难换出任何一个或进行独立测试。将您的数据访问移至新类(查找存储库模式)。

标签: c# sql asp.net sql-server


【解决方案1】:

您可能认为一直创建新连接的成本很高。不是的,有内置的连接池,连接实际上会被重用。因此你应该这样做:

protected void DeleteButton_Click(object sender, EventArgs e)
{
    using (var connection = new SqlConnection(myConnectionString))
    {
        connection.Open();
        using (var command = new SqlCommand("DELETE FROM [Table] where [Id] ='"+Id.Text+"'", connection)
        { 
            command.ExecuteNonQuery();
        }
        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Successfully Deleted');", true);
        disp_data();
}

using 模式负责关闭和处理 SqlConnection 和 SqlCommand。 接下来,您应该摆脱 con 作为类成员,并在您的代码中使用此模式。

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多