Closing SqlConnection and SqlCommand c#(关闭 SqlConnection 和 SqlCommand c#)
问题描述
在我的 DAL 中,我编写如下查询:
In my DAL I write queries like this:
using(SQLConnection conn = "connection string here")
{
SQLCommand cmd = new ("sql query", conn);
// execute it blah blah
}
现在我突然想到我没有明确关闭 SQLCommand 对象.现在我知道使用"块会处理 SQLConnection 对象,但这也会处理 SQLCommand 对象吗?如果不是那么我有一个严重的问题.我将不得不在成千上万行代码上的 SQLCommand 上添加使用",或者在数百种方法上执行 cmd.Close().请告诉我,如果输入 using 或 close 命令会为 Web 应用程序提供更好的内存管理?
Now it just occurred to me that I am not explicitly closing the SQLCommand object. Now I know the 'using' block will take care of the SQLConnection object, but will this also take care of the SQLCommand object? If not than I have a serious problem. I would have to put in the 'using' on the SQLCommand on thousands and thousands of lines of code or do a cmd.Close() on hundreds of methods. Please tell me that if putting in the using or closing the command will provide a better memory management of the web app?
推荐答案
不,using
语句不会处理命令.
No, the using
statement will not take care of the command.
您也应该使用 using
语句来包装命令,因为这将正确地调用它们的 Dispose
:
You should wrap the commands with using
statements as well, since this will properly call Dispose
on them:
using(SQLConnection conn = 'connection string here')
{
using(SQLCommand cmd = new ('sql query', conn))
{
//execute it blah blah
}
}
这篇关于关闭 SqlConnection 和 SqlCommand c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:关闭 SqlConnection 和 SqlCommand c#


基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01