Add SQL Transaction (#12)

添加数据库事务,支持提交和回滚操作。
This commit is contained in:
milimoe 2023-05-10 09:10:29 +08:00 committed by GitHub
parent 690c85f2e2
commit 72b3e5b85e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 50 additions and 16 deletions

View File

@ -30,6 +30,7 @@ namespace Milimoe.FunGame.Server.Utility
private int _UpdateRows = 0;
private DataSet _DataSet = new();
private MySQLConnection? _Connection;
private MySqlTransaction? _Transaction;
private readonly ServerModel? ServerModel;
private readonly bool _IsOneTime = false;
@ -141,6 +142,36 @@ namespace Milimoe.FunGame.Server.Utility
_Connection = new MySQLConnection(out _ServerInfo);
}
/// <summary>
/// 创建一个SQL事务
/// </summary>
public void NewTransaction()
{
_Transaction ??= _Connection?.Connection?.BeginTransaction();
}
/// <summary>
/// 提交事务
/// </summary>
public void Commit()
{
_Transaction?.Commit();
_Transaction = null;
}
/// <summary>
/// 回滚事务
/// </summary>
public void Rollback()
{
_Transaction?.Rollback();
_Transaction = null;
}
/// <summary>
/// 获取客户端名称
/// </summary>
/// <returns></returns>
private string GetClientName()
{
if (ServerModel is null) return "";

View File

@ -20,18 +20,22 @@ namespace Milimoe.FunGame.Server.Utility
try
{
PrepareCommand(Helper, cmd);
Helper.NewTransaction();
updaterow = cmd.ExecuteNonQuery();
if (updaterow > 0)
{
Result = SQLResult.Success;
}
else Result = SQLResult.NotFound;
Helper.Commit();
}
catch (Exception e)
{
ServerHelper.Error(e);
updaterow = -1;
Result = SQLResult.Fail;
Helper.Rollback();
}
return updaterow;
@ -89,17 +93,21 @@ namespace Milimoe.FunGame.Server.Utility
try
{
PrepareCommand(Helper, cmd);
Helper.NewTransaction();
updaterow = cmd.ExecuteNonQuery();
if (updaterow > 0)
{
Result = SQLResult.Success;
}
else Result = SQLResult.NotFound;
Helper.Commit();
}
catch (Exception e)
{
ServerHelper.Error(e);
Result = SQLResult.Fail;
Helper.Rollback();
}
return cmd.LastInsertedId;
@ -110,24 +118,18 @@ namespace Milimoe.FunGame.Server.Utility
/// </summary>
/// <param name="Helper">MySQLHelper</param>
/// <param name="cmd">命令对象</param>
/// <param name="trans">事务</param>
public static void PrepareCommand(MySQLHelper Helper, MySqlCommand cmd, MySqlTransaction? trans = null)
public static void PrepareCommand(MySQLHelper Helper, MySqlCommand cmd)
{
if (Helper.Connection != null)
{
MySqlConnection? conn = Helper.Connection.Connection;
if (conn != null && conn.State != ConnectionState.Open)
conn.Open();
if (conn != null)
{
if (conn.State != ConnectionState.Open) conn.Open();
cmd.Connection = conn;
cmd.CommandText = Helper.Script;
if (trans != null)
{
cmd.Transaction = trans;
}
cmd.CommandType = Helper.CommandType;
if (Helper.Parameters != null)
@ -141,3 +143,4 @@ namespace Milimoe.FunGame.Server.Utility
}
}
}
}