c#实现数据库事务示例分享

时间:2021-05-20


复制代码 代码如下:
using System;
using System.Data.SqlClient;

namespace ExecuteSqlTran
{
class Program
{
class Result<T>
{
public T data;
public string Message;
public bool Success;
public string StackTrace;
}

struct ExecuteableUnit
{
public string SQL;
public SqlParameter[] param;
}

/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
private static Result<int> ExecuteSqlTransaction(params ExecuteableUnit[] executeableUnits)
{
using (SqlConnection connection = new SqlConnection(""))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction = connection.BeginTransaction();
command.Connection = connection;
command.Transaction = transaction;
int result = 0;
try
{
foreach(ExecuteableUnit exeUnit in executeableUnits)
{
command.CommandText = exeUnit.SQL;
if(exeUnit.param.GetLength(1) > 0)
{
foreach(SqlParameter p in exeUnit.param)
command.Parameters.Add(p);
}
result += command.ExecuteNonQuery();
}
transaction.Commit();
}
catch (Exception ex)
{
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
return new Result<int>()
{
Success = false, Message = ex2.Message, StackTrace = ex2.StackTrace
};
}
return new Result<int>()
{
Success = false, Message = ex.Message, StackTrace = ex.StackTrace
};
}
finally
{
// Attempt to roll back the transaction.
try
{
connection.Close();
}
catch (Exception ex)
{
}
}
return new Result<int>()
{
Success = true, data = result
};
}
}

public static void Main(string[] args)
{
}
}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章