如何:使用事务保存数据

更新:2007 年 11 月

使用 System.Transactions 命名空间在事务中保存数据。使用 TransactionScope 对象来参与为您自动管理的事务。

项目不是用对 System.Transactions 程序集的引用创建的,因此您需要向使用事务的项目手动添加引用。

说明:

Windows 2000 和更高版本支持 System.Transactions 命名空间。

实现事务的最简便方法是在 using 语句中实例化 TransactionScope 对象。(有关更多信息,请参见 Using 语句 (Visual Basic)using 语句(C# 参考)。) using 语句内执行的代码将参与事务。

若要提交事务,请调用作为 using 块中最后语句的 Complete 方法。

若要回滚事务,请在调用 Complete 方法之前,引发异常。

有关更多信息,请参见 演练:在事务中保存数据

添加对 System.Transactions dll 的引用

  1. 从“项目”菜单中选择“添加引用”。

  2. 在“.NET”选项卡(SQL Server 项目的“SQL Server”选项卡)上选择“System.Transactions”,并单击“确定”。

    对 System.Transactions.dll 的引用被添加到项目中。

在事务中保存数据

  • 添加代码以在包含事务的 using 语句内保存数据。下面的代码显示如何在 using 语句中创建和实例化 TransactionScope 对象:

    Using updateTransaction As New Transactions.TransactionScope
    
        ' Add code to save your data here.
        ' Throw an exception to roll back the transaction.
    
        ' Call the Complete method to commit the transaction
        updateTransaction.Complete()
    End Using
    
    using (System.Transactions.TransactionScope updateTransaction = 
        new System.Transactions.TransactionScope())
    {
        // Add code to save your data here.
        // Throw an exception to roll back the transaction.
    
        // Call the Complete method to commit the transaction
        updateTransaction.Complete();
    }
    

请参见

任务

演练:在事务中保存数据

概念

“显示数据”概述

其他资源

数据访问入门

连接到 Visual Studio 中的数据

准备应用程序以接收数据

将数据获取到应用程序

在 Windows 应用程序中的窗体上显示数据

在应用程序中编辑数据

验证数据

保存数据