SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;");
//启动一个本地事务
SqlTransaction myTrans = myConnection.BeginTransaction();
//在当前的事务中登记命令
SqlCommand myCommand = myConnection.CreateCommand();
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText="Insert into Region(RegionID,RegionDescription) Values(100,'Description')";
myCommand.ExecuteNonQuery();
myCommand.CommandText="Insert into Region(RegionID,RegionDescription) Values(101,'Description')";
myCommand.ExecuteNonQuery();
myTrans.Commit();
System.Console.WriteLine("Both records are written to database");
}
catch(Exception e)
{
try
{
myTrans.Rollback();
}
catch(SqlException ex)
{
if(myTrans.Connection!=null)
{
Console.WriteLine("An exception " + ex.GetType() + " Was encountered while attempting to roll back the transction.");
}
}
}
finally
{
myConnection.Close();
}