如果在关闭连接之前从未调用transaction.Rollback / Commit会发生什么?

问题描述 投票:1回答:1

如果在关闭连接之前从未调用transaction.Rollback / Commit会发生什么?

public DBStatus InsertUpdateUserProfile(Int64 UserID, W_User_Profile oUser)
{
    MySqlConnection oMySQLConnecion = null;
    MySqlTransaction tr = null;
    DBStatus oDBStatus = new DBStatus();
    try
    {
        oMySQLConnecion = new MySqlConnection(DatabaseConnectionString);
        if (oMySQLConnecion.State == System.Data.ConnectionState.Closed || oMySQLConnecion.State == System.Data.ConnectionState.Broken)
        {
            oMySQLConnecion.Open();
        }

        tr = oMySQLConnecion.BeginTransaction();

        if (oMySQLConnecion.State == System.Data.ConnectionState.Open)
        {
            string Query = @"INSERT INTO user .....................;"
                            INSERT IGNORE INTO user_role ....................;";

            MySqlCommand oCommand = new MySqlCommand(Query, oMySQLConnecion);
            oCommand.Transaction = tr;

            oCommand.Parameters.AddWithValue("@UserID", UserID);                            
            oCommand.Parameters.AddWithValue("@AddressID", oUser.AddressID);                                 
    ................
    ................


            int sqlSuccess = oCommand.ExecuteNonQuery();

            if (sqlSuccess>0)
            {
                tr.Commit();
                oDBStatus.Type = DBOperation.SUCCESS;
                oDBStatus.Message.Add(DBMessageType.SUCCESSFULLY_DATA_UPDATED);
            }
            oMySQLConnecion.Close();
        }
        else
        {
            oDBStatus.Type = DBOperation.ERROR;
            oDBStatus.Message.Add(DBMessageType.ERROR_DUE_TO_NO_DB_CONNECTION);
        }
        return oDBStatus;
    }
    catch (Exception ex)
    {
        if (oMySQLConnecion.State == System.Data.ConnectionState.Open)
        {
            tr.Rollback();
            oMySQLConnecion.Close();
        }
        oDBStatus.Type = DBOperation.ERROR;
        oDBStatus.Message.Add(DBMessageType.ERROR_OR_EXCEPTION_OCCURED_WHILE_UPDATING);
        oDBStatus.InnerException.Add(ex.Message);
        return oDBStatus;
    }
} 

在上面的函数中,如果事务成功,我会执行提交,如果失败并且连接仍然打开,则执行回滚。

如果连接终止,则没有回滚。我读过许多地方,如果连接终止而没有提交(我想要的话),那将是一个自动回滚。这是一种不好的做法吗?我可以在连接建立后添加try-catch,但在每个类似的函数中添加一些代码。真的有必要吗?

mysql asp.net commit rollback
1个回答
1
投票

如果在关闭连接之前从未调用transaction.Rollback / Commit会发生什么?

在MySQL中,事务被回滚。但是其他一些表服务器在连接关闭时提交它。

专业提示:除了作为处理硬崩溃的方法之外,不要依赖此行为。

© www.soinside.com 2019 - 2024. All rights reserved.