从方法返回而不提交事务

时间:2019-01-22 14:55:38

标签: c# sql transactions sqltransaction

具有以下代码,如果我从方法中返回而未在事务对象上调用Commit()会发生什么情况?

var transaction = connection.BeginTransaction();

try
{
    int val;

    var myCommand = new SqlCommand(
        @"SELECT ......",
        connection, transaction);

    using (var reader = myCommand.ExecuteReader())
    {
        if (reader.Read() && !reader.IsDBNull(0))
        {
            if (int.TryParse(reader.GetString(0), out val))
            {
                return val; // <--- this code executes
            }
        }
    }

    transaction.Commit() // <--- this code never executes
}
catch (Exception ex)
{                    

    // Rollback the transaction.
}

0 个答案:

没有答案
相关问题