Monday, February 08, 2010

Rollback, Commit, and Savepoints in ADO.NET

The Sql data provider provides some additional methods for dealing with transactions involving save points. Save points allow you to rollback to a "bookmarked" point in the transaction. Table 5-34 describes these methods.

Table 5-34. Transaction Methods in the Sql Data Provider

METHOD                                     DESCRIPTION

Rollback(SavePoint)                      Performs a roll back on a transaction to the previous database state.

Begin(IsolationLevel)                     Begins a nested database transaction passing the isolation level.

Save(SavePointName)                  Equivalent to the transaction-SQL SAVE TRANSACTION in the Sql server database. Allows you to create a save point so that you can roll back to a particular saved state of the database.

Listing 5-58 shows an example of how savepoints are used in Sql server. As you can see from Listing 5-58, first you establish a connection with the Northwind database and open the connection. After that, by calling BeginTransaction on the connection. You can return a SqlTransaction object, which you can use together with your Command object. To establish the relationship with the command object, you then pass the Transaction object in the constructor of Command.

Now that the transaction is tied to the Command object, you'll save the initial save point to the transaction and then execute the first insertion into the database. After that you assign a new SQL Insert to the CommandText and save the current transaction savepoint before executing the query. This Insert puts "Bob Hope" into the database.

Finally, you assign a new SQL Insert to the CommandText and save the current transaction save point before executing the query. This Insert Puts "Fred" into the database.

Read more: C# Corner

Posted via email from jasper22's posterous