Cannot access SqlTransaction object to rollback in catch block

前端 未结 7 1088
我寻月下人不归
我寻月下人不归 2020-12-02 15:43

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 s

7条回答
  •  半阙折子戏
    2020-12-02 16:21

    using (var Conn = new SqlConnection(_ConnectionString))
    {
        SqlTransaction trans = null;
        try
        {
            Conn.Open();
            trans = Conn.BeginTransaction();
    
            using (SqlCommand Com = new SqlCommand(ComText, Conn, trans))
            {
                /* DB work */
            }
            trans.Commit();
        }
        catch (Exception Ex)
        {
            if (trans != null) trans.Rollback();
            return -1;
        }
    }
    

    or you could go even cleaner and easier and use this:

    using (var Conn = new SqlConnection(_ConnectionString))
    {
        try
        {
            Conn.Open();
            using (var ts = new System.Transactions.TransactionScope())
            {
                using (SqlCommand Com = new SqlCommand(ComText, Conn))
                {
                    /* DB work */
                }
                ts.Complete();
            }
        }
        catch (Exception Ex)
        {     
            return -1;
        }
    }
    

提交回复
热议问题