如何:使用事务保存数据

 

发布日期: 2016年7月

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

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

备注

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

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

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

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

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

添加对 System.Transactions dll 的引用

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

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

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

在事务中保存数据

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

                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();
                }
    
            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
    

请参阅

演练:在事务中保存数据
在 Visual Studio 中将 Windows 窗体控件绑定到数据
Visual Studio 的数据应用程序概述
连接到 Visual Studio 中的数据
准备应用程序以接收数据
将数据获取到应用程序
在 Visual Studio 中将控件绑定到数据
在应用程序中编辑数据
验证数据
保存数据