Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I close an OracleConnection in .NET

Say I have these two objects:

OracleConnection connection = new OracleConnection(connectionString);  
OracleCommand command = new OracleCommand(sql, connection);

To close the connection or Oracle, do I have to call command.Dispose(), connection.Dispose(), or both?

Is this good enough:

using(connection)  
{
    OracleDataReader reader = cmd.ExecuteReader();
    // whatever...
}
like image 376
Mike Comstock Avatar asked Mar 30 '09 18:03

Mike Comstock


1 Answers

Both answers are pretty much on target. You always want to call .Dispose() on any IDisposeable object. By wrapping in a "using" you tall the compiler to always impliment a try/finialy block for you.

1 point of note, if you want to avoid the nesting, you can write the same code like this:

 using (OracleConnection connection = new OracleConnection(connectionString))
 using (OracleCommand command = new OracleCommand(sql, connection))
 using (OracleDataReader reader = cmd.ExecuteReader())
    {
        // do something here
    }
like image 55
Russ Avatar answered Dec 02 '22 05:12

Russ