欢迎访问我的博客 https://javascript.shop

c#中使用事务

原文发布时间为:2009-04-14 —— 来源于本人的百度文章 [由搬家工具导入]

问:为什么要用事务?

答:事务保证要么一组操作执行成功,要么全不执行。。。。

/// <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;
}

posted @ 2017-07-12 00:05  孑孓子  阅读(173)  评论(0编辑  收藏  举报
欢迎访问我的博客 https://javascript.shop