Alvin
Alvin

Reputation: 8519

Transaction rollback error

I am using a ado.net helper class from Here. I don't know how to use transaction using the helper. Below is the code I have tried. Am I doing the right thing? I always hit the This SqlTransaction has completed; it is no longer usable. error.

            Adodb.ConnectionString = "...";

            Adodb db = new Adodb(); 
            SqlTransaction trans = db.BeginTransaction();

            try
            {
                string qry = "UPDATE PSCHCounter SET SeqNo = '0' WHERE CountID = 'PCSTL'";
                db.ExecNonQuery(qry);
                string qry1 = "UPDATE PSCHCounter SET SeqNo = '1' WHERE CountID = 'GJNLP'";
                db.ExecNonQuery(qry1);

                // Commit 
                trans.Commit();
            }
            catch (Exception ex)
            {
                try
                {
                    // Rollback
                    trans.Rollback();
                    // Log exception
                }
                catch (Exception ex2)
                {
                    // Log exception
                }
            }
            finally
            {
                // Close db connection
                db.Dispose();
            }

Thank you.

Upvotes: 0

Views: 759

Answers (1)

mgnoonan
mgnoonan

Reputation: 7200

The problem is you are calling trans.Commit() instead of db.Commit(). This worked for me:

    AdoHelper.ConnectionString = "...";

    using (AdoHelper db = new AdoHelper())
    {
        // Start the transaction
        db.BeginTransaction();

        try
        {
            db.ExecNonQuery("UPDATE FeedItems SET Title = 'Test3' WHERE Id = 456");
            db.ExecNonQuery("UPDATE FeedItems SET Title = 'Test4' WHERE Id = 457");

            // Commit  
            db.Commit();
        }
        catch (Exception ex)
        {
            db.Rollback();
        }
    }

Upvotes: 1

Related Questions