So the following question was posted to a forum I frequent and it serves a good point of illustration:
"I wont to clear all the data from tables in the database. I have studentiDataset, and i tried this code:
Form2.StudentiDataSet.Clear()
Form2.StudentiDataSet.AcceptChanges()
I also tried to add after this code tableadapter update method for all tables but it didn't work.
How can i doo that?
Thanks!"
Remember the basic behavior of Adapters. When the Update method is called, it loops through each row and checks theRowState. Depending on what it finds, a different action is taken.
- The row's RowState is Deleted:
- The adapter looks for a valid Delete command and executes it.
- It calls AcceptChanges on the row unless AcceptChangesOnUpdate is set to false
- If no Delete command is present, it throws an exception
- The row's RowState is Modified:
- The adapter looks for a valid Update command and executes it
- It calls AcceptChanges on the row unless AcceptChangesOnUpdate is set to false
- If no Update command is present, it throws an exception
- The row's RowState is Added:
- The adapter looks for a valid Insert command and executes it
- It calls AcceptChanges on the row unless AcceptChangesOnUpdate is set to false
- If not Insert command is present, it throws an exception
- The row's RowState is Unchanged:
- Nothing happens
Ok pay close attent to the last of these choices. So what happens when you callAcceptChanges? Well, you can call it on a Row, a DataTable or a DataSet. Whenever you call it on aDataRow, the RowState goes back to Unchanged. When you do it to a DataTable, all the rows in the Table are set back to Unchanged. And when done on aDataSet, it sets all the rows in all the tables back to Unchanged.
So what happens if you call Update after AcceptChanges? Unless something is changed in between them, it has a similar effect to calling Thread.Sleep(10); because it basically does nothing.
Now, specifically to this question. AcceptChanges is ensuring that none of the deleted rows are every sent back to the database. However unless you had a specific reason (like a transaction) to do so, then this is probably one of the least efficient ways to delete all the rows for a table. "TRUNCATE TABLE" is the most efficient option and is appropriate unless you need the changes logged. Otherwise, a single "DELETE FROM Whatever" should work. Imagine having 10,000 rows. Truncate or delete do it in one action as opposed to 10,000 of them so unless there's a compelling reason to do otherwise, this should be avoided.
原文地址:http://msmvps.com/blogs/williamryan/archive/2007/02/09/acceptchanges-and-updates-once-more.aspx