关闭 SqlConnection 和 SqlCommand c#

Closing SqlConnection and SqlCommand c#(关闭 SqlConnection 和 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#

基础教程推荐