9.13. Performing Batch Updates with a DataAdapter
Problem
When you use a DataAdapter to
perform updates, it makes a separate
round trip to the server for each row. You want to batch all of the
updates into a single call to the server to improve performance.
Solution
Use the RowUpdating
event raised by the DataAdapter to build a single
batched SQL statement that gets executed using the
ExecuteNonQuery( )
method.
The sample code contains three event handlers:
Form.LoadSets up the sample by creating a
DataAdapterbased on aSELECTstatement of CategoryID, CategoryName, and Description fields of the Categories table in the Northwind database. ACommandBuilderis created to supply updating logic. A method is attached to theRowUpdatingevent of theDataAdapter. A new table is created and filled with the schema and data from the Categories table from the Northwind database. The properties of theAutoIncrementCategoryIDfield are set up. Finally, the default view of the table is bound to the data grid on the form.- Update
Button.Click Calls the
Update( )method of theDataAdapter. TheDataAdapter.RowUpdatinghandler (described next) builds a batch SQL update string, which is executed using theExecuteScalar( )method afterUpdate( )is called.DataAdapter.RowUpdatingIs called before each row is updated by the
DataAdapter. The SQL command to be used to update the row by theDataAdapteris retrieved from theCommandTextproperty of theCommandobject. The parameters for theCommandare iterated ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access