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#
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
