The following code gives an example of using local transaction in ado.net
using System.Transactions;
bool success = false;
SqlConnection conn = null;
SqlTransaction transaction = null;
try
{
conn= new SqlConnection(ConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString;);
conn.Open();
transaction = conn.BeginTransaction(System.Data.IsolationLevel.Serializable);
//Serializable isolation prevents dirty reads, phantom reads, non-repeatable reads by locking large numbers of rows or entire tables.
using (SqlCommand commanda = new SqlCommand(somesql1, conn, transaction))
{
int rowsUpdateda = commanda.ExecuteNonQuery();
if (rowsUpdateda > 0)
{
using (SqlCommand commandb = new SqlCommand(somesql2,conn, transaction))
{
int rowsUpdatedb = commandb.ExecuteNonQuery();
if (rowsUpdatedb > 0)
{
success = true;
}
}
}
}
}
finally
{
if (success)
transaction.Commit();
else
transaction.Rollback();
if (conn!= null)
connection.Close();
}
To use distributed transaction:
//A TransactionOptions object is created to specify the isolation level or timeout for the transaction
TransactionOptions options = new TransactionOptions();
options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
options.Timeout = new TimeSpan(0, 2, 0);
//A Transaction scope defines a block of code that participates in a local or distributed transaction
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
{
using (SqlConnection conna= new SqlConnection(connstring))
{
using (SqlCommand commanda = new SqlCommand(sqla, conna))
{
int rowsUpdateda = commanda.ExecuteNonQuery();
if (rowsUpdateda > 0)
{
using (SqlConnection connb= new SqlConnection(connb))
{
using (SqlCommand commandb = new SqlCommand(sqlb,connb))
{
int rowsUpdatedb = commandb.ExecuteNonQuery();
if (rowsUpdatedb > 0)
{
transactionScope.Complete(); }
}
commandb.Dispose ;// Dispose the second command object.
}
connb.Close;
// Dispose (close) the second connection.
}
} commandb.Dispose; // Dispose the first command object.
} connb.Close ;
// Dispose (close) the first connection.
} TransactionScope.Dispose; // Dispose TransactionScope object, to commit or rollback
Saturday, September 6, 2008
How to use transaction in .Net
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment