6
3月
ADO.NET によるトランザクションの実行
Connection オブジェクトと Transaction オブジェクトを使用して、トランザクションを開始、コミット、およびロールバックすることができます。トランザクションを実行するには、次の手順に従います。
トランザクションを実行するには、次のようにします。
Connection オブジェクトの BeginTransaction メソッドを呼び出してトランザクションの先頭をマークします。BeginTransaction メソッドは Transaction への参照を返します。この参照は、トランザクションに参加する Command オブジェクトに割り当てられます。
実行する Command の Transaction プロパティに Transaction オブジェクトを割り当てます。アクティブな Transaction を持つ Connection 上で Command を実行する場合、Command の Transaction プロパティにその Transaction オブジェクトを割り当てておかないと、例外がスローされます。
必要なコマンドを実行します。
Transaction オブジェクトの Commit メソッドを呼び出して、トランザクションを実行するか、または Rollback メソッドを呼び出してトランザクションをキャンセルします。
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(); }