繁体   English   中英

为什么在提交事务后关闭连接时此 SqlTransaction 会回滚?

[英]Why is this SqlTransaction rolling back upon closing the connection AFTER the transaction has been Committed?

我在事务中有一系列插入,然后是提交。 如果我在关闭连接之前使用 WITH(READUNCOMMITTED) 查询数据库,它会按预期显示。 但是,一旦关闭连接,数据就会消失。 为什么事务实际上没有提交?

using (SqlConnection db = new SqlConnection(connectionstring))
{
    db.Open();
    SqlTransaction transaction = db.BeginTransaction("loadRate");
    try
    {
        int id = 0;
        using (SqlDataAdapter da = new SqlDataAdapter("usp_1", db))
        {
            da.SelectCommand.Transaction = transaction;
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            id = (int)da.SelectCommand.ExecuteScalar();
        }
        int id2 = 0;
        using (SqlDataAdapter da = new SqlDataAdapter("usp_2", db))
        {
            da.SelectCommand.Transaction = transaction;
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            id2 = (int)da.SelectCommand.ExecuteScalar();
        }                    
        transaction.Commit();                    
        Console.WriteLine("Committed data");
    }
    catch (Exception insertExcept)
    {
        Console.WriteLine("Exception: " + insertExcept.Message + ".  Rolling Back");
        try
        {
            transaction.Rollback();
        }
        catch (Exception ex2)
        {                      
            Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
            Console.WriteLine("  Message: {0}", ex2.Message);
        }
    }
    finally
    {
        db.Close();
    }
}   

感谢@mason 为我指明了正确的方向。 其中一个存储过程中有一个未提交的事务,虽然 .net 的 Commit 无法关闭该事务,但关闭连接会自动将其回滚。 感谢您的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM