c# - 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";
}
}
解决方案
一个简单的修复是在 connect.Open() 之前,您可以执行以下操作:
if (connect.State == ConnectionState.Open)
{
connect.Close();
}
此外,正如 Zohar Peled 指出的那样,它可以很好地使用,using (var connect = new SqlConnection(connectionString))
而不是在类级别声明对象。
这样就没有泄漏,并且连接对象在它们的工作完成后立即被释放。
推荐阅读
- python - AWS Lake Formation:grant_permissions:Resource.Table 中的未知参数:“TableWildcard”
- javascript - 将字符串输入与多个字符串 Javascript 进行比较
- python - 跨导入的 Python 函数共享
- reactjs - 反应脚本启动 - 热重载太慢?
- javascript - 遍历符号数组
- c# - 构建问题--“ReferencePath”未定义元数据“CopyLocal”的值
- mysql - 如何通过 Zabbix(在 docker 容器中)监控 MySQL?
- jquery - 如何获取标签的价值?
- python-3.x - 将值作为列表的python字典排序
- visual-studio-code - 带有函数名称的片段