使用事务
隔离级可以在任何时候修改,并在显示改变之前有效。如果在一个事务期间修改隔离级,刚服务器应该对剩下的所有语句应用新的封锁级别。
通过commit或Rollback方法显示地终止一个事务。
事务恢复TransactionScope对象
实现分布式事务处理
bool canCommit = true;
using (TransactionScope ts = new System.Transactions.TransactionScope())
{
// *********************************************************
// Update Northwind on SQL Server 2000
using (SqlConnection conn = new SqlConnection(ConnString))
{
SqlCommand cmd = new SqlCommand(UpdateCmd, conn);
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
// Error handling code goes here
lblMessage.Text += ex.Message;
canCommit &= false;
}
}
// *********************************************************
// Update Numbers on SQL Server 2005
using (SqlConnection conn = new SqlConnection(ConnString05))
{
//SqlCommand cmd = new SqlCommand(RaiseError, conn);
SqlCommand cmd = new SqlCommand(InsertCmd, conn);
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
// Error handling code goes here
lblMessage.Text += ex.Message;
canCommit &= false;
}
}
// Must call to complete; otherwise abort
if (canCommit)
ts.Complete();
}
using (TransactionScope ts = new System.Transactions.TransactionScope())
{
// *********************************************************
// Update Northwind on SQL Server 2000
using (SqlConnection conn = new SqlConnection(ConnString))
{
SqlCommand cmd = new SqlCommand(UpdateCmd, conn);
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
// Error handling code goes here
lblMessage.Text += ex.Message;
canCommit &= false;
}
}
// *********************************************************
// Update Numbers on SQL Server 2005
using (SqlConnection conn = new SqlConnection(ConnString05))
{
//SqlCommand cmd = new SqlCommand(RaiseError, conn);
SqlCommand cmd = new SqlCommand(InsertCmd, conn);
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
// Error handling code goes here
lblMessage.Text += ex.Message;
canCommit &= false;
}
}
// Must call to complete; otherwise abort
if (canCommit)
ts.Complete();
}