There are three steps to using transactions after they are created.It is assigned to the commands that will participate in them, then the commands are executed, and finally the transaction is closed by either committing it or rolling it back.
Assigning Transactions to a Command
Once a transaction has been begun on a connection, all commands executed against that connection must participate in that transaction and if this doesn’t happen automatically—you must set the Transaction property of the command to reference the transaction.
Committing and Rolling Back Transactions
The final step in transaction, processing is to commit or roll back the changes that were made by the commands participating in the transaction. If the transaction is committed, all of the changes will be accepted in the data source. If it is rolled back, all of the changes will be discarded, and the data source will be returned to the state it was in before the transaction began. Transactions are committed using the transaction’s Commit method and rolled back using the transaction’s Rollback method.
- Open the Transactions project from the Visual Studio Start Page or byusing the File menu.
- Double-click Transactions.cs to display the form in the form designer.
- Double-click Create. Visual Studio opens the code editor window and adds the Click event handler.
- Add the following code to the procedure.
TrnNew = this.cnAccessNwind.BeginTransaction();
s = "Isolation Level: ";
s += TrnNew.IsolationLevel.ToString();
- The code creates a new Transaction using the default method, and then displays its IsolationLevel in a message box.
- Press F5 to run the application.