在.net中使用事务

来源:互联网 发布:网络奇兵13dm 编辑:程序博客网 时间:2024/04/30 15:27

 

可以使用 Connection 和 Transaction 对象启动、提交和回滚事务。下面的步骤用于执行事务。
若要执行事务,请执行下列操作:
1.调用 Connection 对象的 BeginTransaction 方法来标记事务的开始。BeginTransaction 方法返回对 Transaction 的引用。该引用将分配给登记在事务中的 Command 对象。
2.将 Transaction 对象分配给要执行的 Command 的 Transaction 属性。如果通过活动的 Transaction 对象对 Connection 执行 Command,但该 Transaction 对象尚未分配给     Command 的 Transaction 属性,则将引发异常。
3.执行所需的命令。
4.调用 Transaction 对象的 Commit 方法来完成事务,或调用 Rollback 方法来取消事务。
以下代码示例使用 Microsoft? SQL Server? 上的 ADO.NET 来演示事务逻辑。

SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;");
myConnection.Open();

// Start a local transaction.
SqlTransaction myTrans = myConnection.BeginTransaction();

// Enlist the command in the current transaction.
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();
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 of type " + ex.GetType() +
                         " was encountered while attempting to roll back the transaction.");
     }
}

Console.WriteLine("An exception of type " + e.GetType() +
                     "was encountered while inserting the data.");
Console.WriteLine("Neither record was written to database.");
}
finally
{
myConnection.Close();
}
原创粉丝点击