// The scenario is coordination between multiple databases.. NET 2.0 uses a new type of TransactionScope for coordination, which is more convenient than the previous COM + coordination.
// You need to reference a new assembly: System. Transactions
// Pay special attention to the fact that the transaction isolation level used by TransactionScope by default is serialized, which may be too strict. Therefore, make necessary adjustments as needed.
// Note: MSDTC service support is still required. Enable it with net start msdtc
TransactionOptions options = new TransactionOptions ();
Options. Timeout = new TimeSpan (0, 0, 60 );
Options. IsolationLevel = IsolationLevel. ReadCommitted;
Using (TransactionScope scope = new TransactionScope (options )){
Try
{
SqlConnection conn1 = new SqlConnection ("server = (local); database = demo; integrated security = true ");
Conn1.Open ();
SqlCommand cmd1 = conn1.CreateCommand ();
Statement 1.commandtext = "insert into Table1 VALUES (3 )";
Statement 1.executenonquery ();
SqlConnection conn2 = new SqlConnection ("server = (local); database = northwind; integrated security = true ");
Conn2.Open ();
SqlCommand cmd2 = conn2.CreateCommand ();
Optional 2.commandtext = "drop table Table1 ";
Listen 2.executenonquery ();
Scope. Complete (); // submit distributed transactions
}
Catch (SqlException ex)
{
MessageBox. Show (ex. Message );
}
}
Note: TransactionScope does not need the so-called Rollback. As long as there is no Complete, it will automatically Rollback when the using statement block jumps out.