关闭SqlConnection和SqlCommand的C# [英] Closing SqlConnection and SqlCommand c#

查看:131
本文介绍了关闭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对象?如果不是我有一个严重的问题。我将不得不把在使用上千种code线和千的SqlCommand或做cmd.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?

推荐答案

没有,在使用语句不会照顾的命令。

No, the using statement will not take care of the command.

您应该使用语句为好,因为这样会正确地调用处置他们用保鲜命令:

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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆