Does SqlCommand.Dispose close the connection?

后端 未结 4 1071
一生所求
一生所求 2020-11-27 15:19

Can I use this approach efficiently?

using(SqlCommand cmd = new SqlCommand(\"GetSomething\", new SqlConnection(Config.ConnectionString))
{
    cmd.Connection         


        
4条回答
  •  有刺的猬
    2020-11-27 16:00

    I use this pattern. I have this private method somewhere in my app:

    private void DisposeCommand(SqlCommand cmd)
    {
        try
        {
            if (cmd != null)
            {
                if (cmd.Connection != null)
                {
                    cmd.Connection.Close();
                    cmd.Connection.Dispose();
                }
                cmd.Dispose();
            }
        }
        catch { } //don't blow up
    }
    

    Then I always create SQL commands and connections in a try block (but without being wrapped in a using block) and always have a finally block as:

        finally
        {
            DisposeCommand(cmd);
        }
    

    The connection object being a property of the command object makes a using block awkward in this situation - but this pattern gets the job done without cluttering up your code.

提交回复
热议问题