gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:22:04 25 4
gpt4 key购买 nike

如果在关闭连接之前从未调用 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,但在每个类似的函数中添加很少的代码。真的有必要吗?

最佳答案

What happens if transaction.Rollback/Commit never called in before closing the connection ?

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

专业提示:不要依赖此行为,除非作为处理硬崩溃的一种方式。

关于mysql - 如果在关闭连接之前从未调用 transaction.Rollback/Commit 会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55796347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com