To use system. transactiions, you do not need to consider simple transactions or distributed transactions.
In SQL Server 2005,. Net creates a local transaction with high performance. However, if it is SQL Server 2000, a distributed transaction is automatically triggered, which may suffer some performance losses.
Using (Transactionscope TS = New Transactionscope ()) // Make the entireCodeBlock into transactional code
{
# Region Compile the code that requires 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 = 'computer 2' where id = 52 " ;
Mycommand. executenonquery ();
Mycommand. commandtext = " Update p_product set name = 'computer 3' where id = 53 " ;
Mycommand. executenonquery ();
MSG = " Successful! " ;
}
Catch (Exception ex)
{
MSG = " Failed: " + Ex. message;
}
Finally
{
Myconnection. Close ();
}
# Endregion
TS. Complete ();
ReturnMSG;
}
Nested transaction processing
Void Rootmethod ()
{
Using (Transactionscope scope Scope = New Transactionscope ())
{
// Operation Code
Sonmethod ();
Scope. Complete ();
}
}
Void Sonmethod ()
{
Using (Transactionscope scope Scope = New Transactionscope ())
{
// Operation Code
Scope. Complete ();
}
}
Transaction Scope
If you want to retain the operations partially executed by the Code and do not want to terminate the use of environment transactions if the operation failsTransactionscospontion. Suppress
Void Methodsuppress ()
{
Using (Transactionscope scope1 = New Transactionscope ())
{
Try
{
// Start a non-transaction range
Using (Transactionscope scope2 = New Transactionscope (Transactionscospontion. Suppress))
{
// Code not controlled by transactions
}
// Back to transaction processing from here
}
Catch
{}
}
}