读书笔记:《亮剑 .Net》——System.Transactions 事务处理
使用System.Transactiions不需要考虑是简单事务还是分布式事务。
在SQL Server 2005下.Net会创建一个Local Transaction,性能非常高。但是如果是SQL Server 2000,则会自动激发一个分布式事务,在性能上会受一些损失
using (TransactionScope ts = new TransactionScope())//使整个代码块成为事务性代码
{
#region 在这里编写需要具备Transaction的代码
string msg = "";
string conString = "data source=127.0.0.1;database=codematic;user id=sa;password=";
SqlConnection myConnection = new SqlConnection(conString);
myConnection.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
try
{
myCommand.CommandText = "update P_Product set Name='电脑2' where Id=52";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "update P_Product set Name='电脑3' where Id=53";
myCommand.ExecuteNonQuery();
msg = "成功!";
}
catch (Exception ex)
{
msg = "失败:" + ex.Message;
}
finally
{
myConnection.Close();
}
#endregion
ts.Complete();
return msg;
}
{
#region 在这里编写需要具备Transaction的代码
string msg = "";
string conString = "data source=127.0.0.1;database=codematic;user id=sa;password=";
SqlConnection myConnection = new SqlConnection(conString);
myConnection.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
try
{
myCommand.CommandText = "update P_Product set Name='电脑2' where Id=52";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "update P_Product set Name='电脑3' where Id=53";
myCommand.ExecuteNonQuery();
msg = "成功!";
}
catch (Exception ex)
{
msg = "失败:" + ex.Message;
}
finally
{
myConnection.Close();
}
#endregion
ts.Complete();
return msg;
}
嵌套的事务处理
void RootMethod()
{
using (TransactionScope scope = new TransactionScope())
{
//操作代码
SonMethod();
scope.Complete();
}
}
void SonMethod()
{
using (TransactionScope scope = new TransactionScope())
{
//操作代码
scope.Complete();
}
}
{
using (TransactionScope scope = new TransactionScope())
{
//操作代码
SonMethod();
scope.Complete();
}
}
void SonMethod()
{
using (TransactionScope scope = new TransactionScope())
{
//操作代码
scope.Complete();
}
}
事务范围
如果想保留代码部分执行的操作,并在失败的情况下不希望终止环境事务使用TransactionScopeOption.Suppress
void MethodSuppress()
{
using (TransactionScope scope1 = new TransactionScope())
{
try
{
//开始一个非事务范围
using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress))
{
//不受事务控制代码
}
//从这里开始又回归事务处理
}
catch
{ }
}
}
{
using (TransactionScope scope1 = new TransactionScope())
{
try
{
//开始一个非事务范围
using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress))
{
//不受事务控制代码
}
//从这里开始又回归事务处理
}
catch
{ }
}
}