【问题标题】:Using statement in c# does not close the connection. Why? [duplicate]c# 中的 using 语句不会关闭连接。为什么? [复制]
【发布时间】:2019-12-20 15:02:27
【问题描述】:

我正在创建一个 crud gridview 网页,并在我的代码中使用 ASP.NET 中的“使用”语句,因为我了解到它会自动转换其中的代码,因此我不必使用 connect.Close();

但是,我仍然收到一个错误:

System.InvalidOperationException:连接未关闭。连接的当前状态为打开。

我尝试输入connection.Close();,但仍然出现同样的错误。

这是我的代码。谁能帮我解决这个问题?非常感谢

void PopulateGridView()
{
    using (connect)
    {
        connect.Open();
        adapter = new SqlDataAdapter("SELECT * FROM RetailInfo", connect);
        table = new DataTable();
        adapter.Fill(table);
    }

    if(table.Rows.Count > 0)
    {
        RetailInfoGridView.DataSource = table;
        RetailInfoGridView.DataBind();
    } 
    else
    {
        table.Rows.Add(table.NewRow());
        RetailInfoGridView.DataSource = table;
        RetailInfoGridView.DataBind();
        RetailInfoGridView.Rows[0].Cells.Clear();
        RetailInfoGridView.Rows[0].Cells.Add(new TableCell());
        RetailInfoGridView.Rows[0].Cells[0].ColumnSpan = table.Columns.Count;
        RetailInfoGridView.Rows[0].Cells[0].Text = "No record Found";
    }
}

【问题讨论】:

  • 该连接变量在您的应用程序的其他地方再次使用
  • 错误发生在哪一行? connectSystem.Data.SqlClient.SqlConnection 类型的吗?
  • using (connect) 应该是 using (var connect = new SqlConnection(connectionString)) 顺便说一句,adapter.Fill 将在连接关闭时打开连接,因此您不需要 connect.Open() 行。
  • 非常感谢您的帮助。我解决了。他是对的。我使用了可变连接 3 次。非常感谢!

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


【解决方案1】:

一个简单的修复是在connect.Open()之前,你可以这样做:

if (connect.State == ConnectionState.Open)
{
    connect.Close();
}

此外,正如 Zohar Peled 所指出的那样,使用 using (var connect = new SqlConnection(connectionString)) 而不是在类级别声明对象很好。

这样就不会发生泄漏,并且连接对象会在它们的工作完成后立即被释放。

【讨论】:

    【解决方案2】:

    替换这部分

     using (connect)
        {
           connect.Open();
            adapter = new SqlDataAdapter("SELECT * FROM RetailInfo", connect);
            table = new DataTable();
            adapter.Fill(table);
         }
    

    using (connect)
        {
            if (connect.State == ConnectionState.Open)
            connect.Close();
            connect.Open();
            adapter = new SqlDataAdapter("SELECT * FROM RetailInfo", connect);
            table = new DataTable();
            adapter.Fill(table);
            connect.Close();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-13
      • 2012-12-11
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      • 2010-10-09
      • 1970-01-01
      • 2012-04-20
      相关资源
      最近更新 更多