Nội dung Text: Using Transactions with a DataSet (SQL)
Using Transactions with a DataSet (SQL)
In Chapter 3, "Introduction to Structured Query Language," you saw how you can group
SQL statements together into transactions. The transaction is then committed or rolled
back as one unit. For example, in the case of a banking transaction, you might want to
withdraw money from one account and deposit it into another account. You would then
commit both of these changes as one unit, or if there's a problem, rollback both changes.
In Chapter 8, "Executing Database Commands," you saw how to use a Transaction object
to represent a transaction.
As you know, a DataSet doesn't have a direct connection to the database. Instead, you use
the Fill() and Update() methods of a DataAdapter to pull and push rows from and to the
database to your DataSet respectively. In fact, a DataSet has no "knowledge" of the
database at all. A DataSet simply stores a disconnected copy of the data. Because of this,
a DataSet doesn't have any built-in functionality to handle transactions.
How then do you use transactions with a DataSet? The answer is you must use the
Transaction property of the Command objects stored in a DataAdapter.
Using the DataAdapter Command Object's Transaction Property
A DataAdapter stores four Command objects that you access using the SelectCommand,
InsertCommand, UpdateCommand, and DeleteCommand properties. When you call the
Update() method of a DataAdapter, it runs the appropriate InsertCommand,
UpdateCommand, or DeleteCommand.
You can create a Transaction object and set the Transaction property of the Command
objects in your DataAdapter to this Transaction object. When you then modify your
DataSet and push the changes to the database using the Update() method of your
DataAdapter, the changes will use the same Transaction.
The following example creates a SqlTransaction object named mySqlTransaction and sets
the Transaction property of each of the Command objects in mySqlDataAdapter to
SqlTransaction mySqlTransaction =
mySqlDataAdapter.SelectCommand.Transaction = mySqlTransaction;
mySqlDataAdapter.InsertCommand.Transaction = mySqlTransaction;
mySqlDataAdapter.UpdateCommand.Transaction = mySqlTransaction;
mySqlDataAdapter.DeleteCommand.Transaction = mySqlTransaction;
Each of the Command objects in mySqlDataAdapter will now use mySqlTransaction.
Let's say you added, modified, and removed some rows from a DataTable contained in a
DataSet named myDataSet. You can push these changes to the database using the
All your changes to myDataSet are pushed to the database as part of the transaction in
mySqlTransaction. You can commit those changes using the Commit() method of
You could also roll back those changes using the Rollback() method of
Note A transaction is rolled back by default; therefore, you should always explicitly
commit or roll back your transaction using Commit() or Rollback() to make it clear
what your program is intended to do.