Search code examples
c#.netusingoledbconnectiondisposing

Disposing connection, command, adapter


When I am querying the database from my c# code I usually use something like this construction:

using (var connection = new OleDbConnection(connStr))
using (var command = new OleDbCommand(query, connection))
using (var adapter = new OleDbDataAdapter(command))
{///}

Should I actually use all this 'using' or it will be enough to dispose only connection and all related objects will be disposed too?


Solution

  • it will be enough to dispose only connection and all related objects will be disposed too?

    No. Disposing connection will only dispose the connection object.

    Generally it is a safe practice to dispose every object that implements IDisposable. (One more thing, disposing Command object will not dispose the related connection object)