c# - 关闭 SqlConnection 和 SqlCommand c#

标签 c# ado.net garbage-collection using-statement

在我的 DAL 中,我这样写查询:

using(SQLConnection conn = "connection string here")
{
    SQLCommand cmd = new ("sql query", conn);
    // execute it blah blah
}

现在我突然想到我没有明确关闭 SQLCommand 对象。现在我知道“using” block 会处理 SQLConnection 对象,但这是否也会处理 SQLCommand 对象?如果不是,那我就有严重的问题了。我将不得不在成千上万行代码的 SQLCommand 上输入“使用”,或者在数百种方法上执行 cmd.Close()。请告诉我,如果放入 using 或 closing 命令将提供更好的网络应用程序内存管理?

最佳答案

SqlConnection 不了解SqlCommand,因此您应该自行关闭它:

using (SqlConnection conn = new SqlConnection("connection string here"))
using (SqlCommand cmd = new SqlCommand("sql query", conn))
{
    // execute it blah blah
}

关于c# - 关闭 SqlConnection 和 SqlCommand c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3370408/

相关文章:

c# - 设置 Visual Studio 的环境变量以调试项目

c# - 如何以编程方式忽略C#中的语法错误

c# - Hangfire 加载程序集失败

c# - 如何在 ASP.NET 中编辑、更新和删除 GridView 中的行

java - 为 CPU 缓存友好性调整 Java 类

c# - EF 代码优先 - 超时已过。完成前超时时间已过

c# - 如何将 sqlparameter 传递给 IN()?

c# - ADO.Net DataReader 超时问题

java - SLinkedList中removeFirst()方法在java中的实现

python - 在 Python 中,每个对象可以调用 `__del__` 多少次?