首页 > 解决方案 > c# 中的 using 语句不会关闭连接。为什么?

问题描述

我正在创建一个 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";
    }
}

标签: c#asp.netsql-serverusing

解决方案


一个简单的修复是在 connect.Open() 之前,您可以执行以下操作:

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

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

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


推荐阅读