使用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;
}
嵌套的交易處理
void RootMethod()
{
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
{ }
}
}