C# 事务
时间:2011-04-19 来源:希望你喜欢
/// <summary>
/// 在一个事务中执行一组任务
/// </summary>
/// <param name="dataAccesses">一组任务</param>
/// <returns>成功返回 true ; 否则 false</returns>
public static bool BatchExecuteNonQuery(params DataAccess[] dataAccesses)
{
bool Success = false;
DbConnection connection = dataAccesses[0].Connection;
if (connection.State != ConnectionState.Open)
connection.Open();
DbTransaction trans = connection.BeginTransaction(IsolationLevel.ReadCommitted);
try
{
foreach (DataAccess dataAccess in dataAccesses)
{
dataAccess.Command.Connection = connection;
dataAccess.Command.Transaction = trans;
dataAccess.Command.ExecuteNonQuery();
}
trans.Commit();
Success = true;
}
catch (Exception e)
{
trans.Rollback();
throw e;
}
finally
{
dataAccesses[0].Connection.Close();
}
return Success;
}