views:

842

answers:

1

Suppose I am doing the following:

using (OracleConnection conn = new OracleConnection(connStr))
{
    OracleTransaction trans = conn.BeginTransaction();
    OracleCommand command = new OracleCommand(cmdTxt, conn, trans);
    // this statement is executed in a transaction context:
    command.ExecuteNonQuery();
}
// the using statement will dispose and thus close the connection.
// a rollback is done implicitly

Although I did not executed transaction.Rollback(), my tests showed that a rollback is done implicitly.

My question is: Will this code leak connections or anything else?

Edit1: I am the System.Data.OracleClient namespace.

Edit2: This is a contrieved example code. The more realistic scenario is when within the using statement an exception occures and the Commit() statement is not executed yet.

Edit3: From the answer I think that this is favorable:

using (OracleConnection conn = new OracleConnection(connStr))
using (OracleTransaction trans = conn.BeginTransaction())
using (OracleCommand command = new OracleCommand(cmdTxt, conn, trans))
{
    command.ExecuteNonQuery();
    trans.Commit();
}

Should cleanly dispose anything and make clear what is happening.

+1  A: 

It will not leak. The using clause guarantees that the OracleConnection will be disposed, regardless of whether the command completes successfully or fails with an exception, and it will take the transaction with it.

But since OracleTransaction is IDisposable, it would probably be good form to put a using clause around the transaction as well, e.g.

using (OracleTransaction trans = conn.BeginTransaction())
{
  // ...
  trans.Commit();
}

This will make it clearer to readers of the code that the transaction is being cleaned up; in particular, it may become important if a subsequent enhancement performs multiple transactions on the same connection.

Also, as per John's comment below, you should put a using statement around the OracleCommand, so that it can be cleaned up promptly.

itowlson
Same with OracleCommand, I suspect. Anything disposable needs to be disposed, probably in a using block.
John Saunders
Thanks John -- updated.
itowlson