是否需要处置SqlConnection和SqlCommand? [英] Is it necessary to dispose SqlConnection as well as SqlCommand?

查看:145
本文介绍了是否需要处置SqlConnection和SqlCommand?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有必要分别处理SqlConnection和SqlCommand?

Is it necessary to separately dispose of a SqlConnection as well as a SqlCommand?

我正在对应用程序进行一些维护工作,发现以下代码:

I'm doing some maintenance work on an application and found the following code:

public void CallStoredProc(string storedProcName)
{
    using (SqlCommand command = new SqlCommand(storedProcName, CreateConnection()))
    {
        command.CommandType = CommandType.StoredProcedure;
        command.Connection.Open();

        // Additional code here.

        command.ExecuteNonQuery();
    }
}

在正常情况下,此操作将正确清理SqlConnection吗以及是否有错误?还是我们必须将代码更改为以下内容:

Will this clean up the SqlConnection properly, under normal circumstances as well as if there is an error? Or would we have to alter the code to something like:

public void CallStoredProc(string storedProcName)
{
    using (SqlConnection connection = CreateConnection())
    {
        using (SqlCommand command = new SqlCommand(storedProcName, connection))
        {
            command.CommandType = CommandType.StoredProcedure;
            command.Connection.Open();

            // Additional code here.

            command.ExecuteNonQuery();
        }
    }
}


推荐答案

是的,您将必须分别处理连接。您还可以在源代码 SqlCommand.Dispose()不会关闭或释放其使用的连接(顺便说一句,这很不好,因为您无法使用相同的连接)。

Yes, you will have to dispose (of) the connection separately. You can also see this in the source code: SqlCommand.Dispose() does not close or dispose the connection it uses (by the way, that would be bad anyway as you could not execute multiple commands with the same connection).

这篇关于是否需要处置SqlConnection和SqlCommand?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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