Share via


ADO.NET によるトランザクションの実行

Connection オブジェクトと Transaction オブジェクトを使用して、トランザクションを開始、コミット、およびロールバックすることができます。トランザクションを実行するには、次の手順に従います。

トランザクションを実行するには、次のようにします。

  1. Connection オブジェクトの BeginTransaction メソッドを呼び出してトランザクションの先頭をマークします。BeginTransaction メソッドは Transaction への参照を返します。この参照は、トランザクションに参加する Command オブジェクトに割り当てられます。
  2. 実行する CommandTransaction プロパティに Transaction オブジェクトを割り当てます。アクティブな Transaction を持つ Connection 上で Command を実行する場合、CommandTransaction プロパティにその Transaction オブジェクトを割り当てておかないと、例外がスローされます。
  3. 必要なコマンドを実行します。
  4. Transaction オブジェクトの Commit メソッドを呼び出して、トランザクションを実行するか、または Rollback メソッドを呼び出してトランザクションをキャンセルします。

Microsoft® SQL Server™ で ADO.NET を使用するトランザクション ロジックを次のサンプル コードに示します。

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

' Start a local transaction.
Dim myTrans As SqlTransaction = myConnection.BeginTransaction()

' Enlist the command in the current transaction.
Dim myCommand As SqlCommand = 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 e As Exception
  Try
    myTrans.Rollback()
  Catch ex As SqlException
    If Not myTrans.Connection Is Nothing Then
      Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
                        " was encountered while attempting to roll back the transaction.")
    End If
  End Try

  Console.WriteLine("An exception of type " & e.GetType().ToString() & _
                    "was encountered while inserting the data.")
  Console.WriteLine("Neither record was written to database.")
Finally
  myConnection.Close()
End Try
[C#]
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();
}

参照

.NET Framework データ プロバイダによるデータのアクセス | OleDbConnection クラス | OleDbTransaction クラス | SqlConnection クラス | SqlTransaction クラス | OdbcConnection クラス | OdbcTransaction クラス