Adrya
Adrya

Reputation: 3607

Using and transactions

Please let me know if the bellow code is correct. I mean connection is closed and disposed and transaction is closed and disposed and rolled back in case of exception. Any other suggestions are welcome.

Thank you, Adrya

using (FbConnection c = new FbConnection(m_connection))
{
    c.Open();
    using (FbTransaction trans = c.BeginTransaction())
    {
        using (FbCommand cmd = new FbCommand("DELETE_MESSAGES_QUEUE", c, trans))
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add("INQUEUENAME", queueName);

            cmd.ExecuteNonQuery();
        }
        using (FbCommand cmd = new FbCommand("DELETE_QUEUE", c, trans))
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add("INQUEUENAME", queueName);

            cmd.ExecuteNonQuery();
        }
        trans.Commit();
    }
}

Upvotes: 2

Views: 3857

Answers (3)

cincura.net
cincura.net

Reputation: 4150

Yes it is. The Dispose method will dispose the underlying transaction and that, if transaction is still running, does the rollback (i.e. here).

If the exception happens on server side (or i.e. the connection is lost), then server rollbacks the transaction.

Upvotes: 0

Magnus
Magnus

Reputation: 46977

I would probably use a transaction scope instead, not sure of disposing a transaction rolls it back, TransactionScope does however.

using (var scope = new TransactionScope())
using (var c = new FbConnection(m_connection))
{
        using (var cmd = new FbCommand("DELETE_MESSAGES_QUEUE", c))
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add("INQUEUENAME", queueName);

            cmd.ExecuteNonQuery();
        }
        using (var cmd = new FbCommand("DELETE_QUEUE", c))
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add("INQUEUENAME", queueName);

            cmd.ExecuteNonQuery();
        }
        scope.Complete();
}

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039348

Yes, this code seems perfectly fine.

Upvotes: 2

Related Questions