Is it necessary to dispose SqlConnection as well as SqlCommand?

微笑、不失礼 提交于 2019-12-02 08:52:07

问题


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();
    }
}

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();
        }
    }
}

回答1:


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).




回答2:


yes , it is necessary to dispose the sqlconnection and sqlcommand object after your piece of code gets executed.

Now, there are two ways by which you can achieve this:

  1. Write your code in using statement which will take care of disposing the objects, as sqlconnection and sqlcommand implements the IDisposable interface which takes care of disposing the objects..
  2. by calling .close() method explicitly on sqlconnection object.


来源:https://stackoverflow.com/questions/33116834/is-it-necessary-to-dispose-sqlconnection-as-well-as-sqlcommand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!