Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (14.07 KB, 2 trang )
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
mySqlTransaction:
SqlTransaction mySqlTransaction =