0

I usually use below code, should it be right ?

 using (SqlConnection myConn = new SqlConnection(ConnectionString))
     {
         using (SqlCommand cmd = new SqlCommand(sqlString, myConn))
         {
             myConn.Open();
             rows = cmd.ExecuteNonQuery();
         }
         // TO DO .
     }

Which one is prefer? Please tell me the difference between them. In my opinion: when Pooling is false both close and dispose will shut down the connection. When Pooling is true close won't shut down the collection ,but dispose would.

  • _"shut down the collection"_ ?? You mean the connection. If pooling is enabled `Close` will not close the physical connection but just tell the pool that this connection is ready to be used. You should prefer the `using`-statement on everything that implements `IDisposable` anyway. `connection.Dispose` will call `connection.Close` implicitly. – Tim Schmelter Nov 12 '15 at 14:59
  • Thanks dude,i got it –  Nov 12 '15 at 15:06

1 Answers1

0

When you call Dispose() on a SqlConnection, internally, it calls Close(), too.

There is no worry - you are free to use Close() manually, or just let Dispose() do it for you.

Marshal
  • 6,551
  • 13
  • 55
  • 91