Search code examples
c#ado.netidisposablesqlconnectionsqlcommand

Disposing SqlCommand


Because SqlCommand implements IDisposable, I would normally approach an ADO query as follows.

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
    // Execute command, etc. here
}

However, what if I need to execute multiple commands during a single connection? Do I really need a new using block for each command?

The examples I found from Microsoft don't use a using block for SqlCommands (or even call Dispose()). What are best practices regarding disposing SqlCommand?


Solution

  • Sure, best practice is to dispose them.

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
       connection.Open();
    
       using (SqlCommand command1 = new SqlCommand(query1, connection))
       {
          // Execute command, etc. here
       }
    
       using (SqlCommand command2 = new SqlCommand(query2, connection))
       {
          // Execute command, etc. here
       }
    
       using (SqlCommand command3 = new SqlCommand(query3, connection))
       {
          // Execute command, etc. here
       }
    }
    

    MSDN probably doesn't show it because it's not really needed in case of SqlCommand. But in my opinion it's bad from microsoft to not use this pattern on every object that implements IDdisosable because people aren't getting used to it.