IDbTransaction 接口

定义

表示在数据源中执行的事务,由访问关系数据库的 .NET 数据提供程序实现。

C#
public interface IDbTransaction : IDisposable
派生
实现

示例

以下示例创建派生类 SqlConnectionSqlTransaction和 的实例。 它还演示如何使用 BeginTransactionCommitRollback 方法。

C#
private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction();

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();

            // Attempt to commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction.
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }
        }
    }
}

注解

接口 IDbTransaction 允许继承类实现 Transaction 类,该类表示将在数据源中执行的事务。 有关事务类的详细信息,请参阅 事务和并发

应用程序不会直接创建 接口的 IDbTransaction 实例,而是创建继承 的类的 IDbTransaction实例。

继承 IDbTransaction 的类必须实现继承的成员,并且通常定义其他成员以添加特定于提供程序的功能。 例如, IDbTransaction 接口定义 Commit 方法。 类反过来 OleDbTransaction 会继承此属性,并定义 Begin 方法。

实施者说明

若要促进.NET Framework数据提供程序之间的一致性,请以 Transaction 的形式Prv命名继承类,其中 Prv 是给定给特定.NET Framework数据提供程序命名空间中所有类的统一前缀。 例如, Sql 是 命名空间中 类的SqlTransactionSystem.Data.SqlClient前缀。

属性

Connection

指定要与事务关联的 Connection 对象。

IsolationLevel

为该事务指定 IsolationLevel

方法

Commit()

提交数据库事务。

Dispose()

执行与释放或重置非托管资源关联的应用程序定义的任务。

(继承自 IDisposable)
Rollback()

从挂起状态回滚事务。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1