C# - Rollback SqlTransaction in catch block - Problem with object accessability

Posted by Marks on Stack Overflow See other posts from Stack Overflow or by Marks
Published on 2010-05-26T10:36:51Z Indexed on 2010/05/26 10:41 UTC
Read the original article Hit count: 252

Filed under:
|
|
|

Hi there.
I've got a problem, and all articles or examples i found seem to not care about it. I want to do some database actions in a transaction. What i want to do is very similar to most examples:

using (SqlConnection Conn = new SqlConnection(_ConnectionString))
{
    try
    {
        Conn.Open();
        SqlTransaction Trans = Conn.BeginTransaction();

        using (SqlCommand Com = new SqlCommand(ComText, Conn))
        {
            /* DB work */
        }
    }
    catch (Exception Ex)
    {
        Trans.Rollback();
        return -1;
    }
}

But the problem is, that the SqlTransaction Trans is declared inside the try block. So it is not accessable in the catch() block. Most examples just do Conn.Open() and Conn.BeginTransaction() before the try block. But i think thats a bit risky, since both can throw multiple exceptions.

Am I wrong, or do most people just ignore this risk? Whats the best solution to be able to rollback, if an exception happens.

Thanks in advance, Marks

© Stack Overflow or respective owner

Related posts about c#

Related posts about sql