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.Load
Sets up the sample by creating a
DataAdapter
based on aSELECT
statement of CategoryID, CategoryName, and Description fields of the Categories table in the Northwind database. ACommandBuilder
is created to supply updating logic. A method is attached to theRowUpdating
event 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 theAutoIncrement
CategoryID
field 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.RowUpdating
handler (described next) builds a batch SQL update string, which is executed using theExecuteScalar( )
method afterUpdate( )
is called.DataAdapter.RowUpdating
Is called before each row is updated by the
DataAdapter
. The SQL command to be used to update the row by theDataAdapter
is retrieved from theCommandText
property of theCommand
object. The parameters for theCommand
are iterated ...
Get ADO.NET Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.