Verteilte Transaktion mit TransactionScope
Zu Abschnitt 5.3.4 des Buchs
Das folgende Beispiel zeigt die Verwendung eines TransactionScope-Objekts zur Abwicklung einer
verteilten Transaktion.
In einer using-Anweisung wird ein Codeblock mit einem lokalen TransactionScope-Objekt angelegt.
Innerhalb dieses Codeblocks werden alle Datenbankanweisungen als Transaktion ausgeführt.
Am Ende des Blocks erfolgt die Bestätigung durch Complete. Im Falle einer Ausnahme
wird der Block ohne Aufruf von Complete verlassen und alle Änderungen werden zurückgenommen.
5-3-4-TransactionScopeSample.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
namespace Chapter5
{
class TransactionScopeSample
{
static void Main(string[] args)
{
string connStr1 = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=Northwind; " +
"Integrated Security=True;";
string connStr2 = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=NETBOOK; " +
"Integrated Security=True;";
SqlConnection con1 = null;
SqlConnection con2 = null;
try
{
using (TransactionScope transScope =
new TransactionScope(TransactionScopeOption.RequiresNew))
{
// Verbindungen anlegen und oeffnen
con1 = new SqlConnection(connStr1);
con2 = new SqlConnection(connStr2);
con1.Open();
con2.Open();
//----- Extension in Employees aendern
IDbCommand cmd1 = con1.CreateCommand();
cmd1.CommandText = "UPDATE Employees SET Extension=1234 WHERE LastName = 'King'";
cmd1.ExecuteNonQuery();
//----- Phone in Contact aendern
IDbCommand cmd2 = con2.CreateCommand();
cmd2.CommandText = "UPDATE Contact SET Phone=1234 WHERE Name = 'King'";
cmd2.ExecuteNonQuery();
// Aenderungen bestaetigen
transScope.Complete();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
try
{
// Verbindungen schliessen
con1.Close();
con2.Close();
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
}
}
}
}
|
|