Use datasets to change data and save changes to the database

Source: Internet
Author: User

RowState is

DataRow An important attribute that represents the Current state of the DataRow. RowState has Added, Modified, unchanged, Deleted, Detached, respectively, indicating that the DataRow was added, modified, unchanged, deleted, detached from the table. In calling some method or some action, these states can be converted to each other.

dataadapt ER

datarow dataadapter Span class= "Apple-converted-space" > will datarow dataadapter dbcommand . If you write a DELETE statement in UpdateCommand or perform a stored procedure with a delete operation, the status is Modified datarow

Datatable.acceptchanges's understanding

How can OleDbDataAdapter not update the database?

String Tbname = ds. Tables[0]. TableName;

String tem = ds. Tables[0]. rows[0]["Bomid"]. ToString ();

DataRow dr = ds. Tables[0]. NewRow ();

dr["Bomid"] = "104";

dr["Quantity"] = 10;

Ds. Tables[0]. Rows.Add (DR);

Ds. AcceptChanges ();

Oleadaper.update (Ds,ds. Tables[0]. TableName);//Is this the update database?

Remove DS. AcceptChanges (); it's all right.

What is this for?

Oleadaper.update: Update command for RowState equal to deleted/inserted/updated call response for DataRow

Ds. AcceptChanges (): Changes the RowState of all DataRow to unchanged, so there is no data update

or change to

Oleadaper.update (Ds,ds. Tables[0]. TableName);//

Ds. AcceptChanges ();

Reverse order for other purposes

When a DataRow object has just been created and its state is detached, it is an isolated existence, so after the DataRow has been built, the cells in the DataRow are populated with data and passed DATATABLE.ROWS.ADD (DataRow) The Datatable,datarow method adds this DataRow to the DataTable and the status of the DataRow is changed to added. When this DataRow has been modified, the DataRow state is converted to modified, When the DataRow is deleted using the Datarow.delete () method, the DataRow state will be converted to deleted, but this line still exists in the DataTable, but the state is changed, when the number of rows is viewed with DataTable.Rows.Count, the same as before the deletion. This DataRow is removed from the DataTable only after the Datatable.remove (DataRow) method is called, and the state is returned to the detached orphan state.

Once you call theafter the Datatable.acceptchanges () method, all rows are processed differently depending on the state, Added, Modified, unchanged will retain the current value, will not change, The deleted will be removed from the DataTable and all the rows will be in the same state as unchanged。 When a DataTable is populated from the DataAdapter.Fill (dataset,datatable) method, the Fill () method automatically calls the AcceptChanges () method, which resets the row state of the DataTable to unchanged. Also, if the DataTable specified in the Fill method does not exist for the dataset to be populated, a DataTable with the same structure as the data source table is generated and the data is populated

There are two ways to delete a DataRow object from a DataTable object: The DataRowCollection object'sRemove MethodAnd the DataRow object'sDelete Method。 The Remove method removes the DataRow from the DataRowCollection andThe delete method only marks the row for deletion, and the actual deletion occurs when the application calls the AcceptChanges method.。 By using Delete, you can programmatically check which rows are marked for deletion before you actually delete them. If the row is marked for deletion, its RowState property is set to Deleted.

When using a dataset or DataTable with DataAdapter and relational data sources,remove rows with the Delete method of the DataRow. The Delete method simply marks the row as Deleted in the DataSet or DataTable and does not remove it. DataAdapter, when encountering a row marked Deleted, executes its DeleteCommand method to delete the row in the data source, but to delete the row in the dataset or DataTablepermanently remove the row with the AcceptChanges method。If you use Remove to delete the row, it is completely removed from the table, but DataAdapter does not delete the row in the data source.

How to use datasets to add, modify, and delete a data in a database

First we open a connection

String myConnString = "Driver={microsoft Access Driver (*.mdb)}; Dbq=c:/test/test.mdb; ";
String Strcomm = "SELECT * from UserList";
SqlConnection conn = new SqlConnection (myConnString);
SqlDataAdapter mycomm = new SqlDataAdapter (strcomm,myconnection);

Here we are simply storing the contents of a table in a dataset for ease of interpretation:

DataSet myDataSet = new DataSet ();
Mycomm.fil (myDataSet, "userlist");

At this point we get a DataSet with UserList table data. Before we explain the dataset, we also need to understand the structure of the dataset, which is the structure tree of the dataset.

DataSet
Relationscollection
ExtendedProperties
Tablescollection
DataTables
 
Rows
Columns
Other
Since we are studying the DataTable, the rest of us do not care about them for the time being. A dataset contains multiple DataTable, and a DataTable contains multiple row, which is the basis for manipulating a dataset:

Add Data

Add a data, from the above list we can see, in fact, is to add a row row, here we also show how to add a row of data, we program everything with a dataset as the vertex, hehe, if tablescollection,rowscollection down, There are some annoying dt. AcceptChanges the invocation of these methods, it's annoying, it's time to get it done.

DataRow dr=mydataset.tables["UserList"]. NewRow ();
dr["UserName"] = "Zhou Xun";
dr["ReMark"] = "100";
dr["Comment"] = "beautiful mm";
MyDataSet.Tables.Rows.Add (DR);

In the first line, we set up a new data row that is used to store our newly added data. We then add the data we need in this data row. dr["UserName"] indicates that the UserName field is added, you can use dr[1] to add information, but this requires us to know in advance where the field is located in the data table, and it is difficult to know the corresponding situation of the data we added without knowing the structure of the data table. So it's better to use the field name.

Finally, we use the Rowscollection Add method to add our new line to the data table.

Modifying Data

Once you know how to add data, it's easy to modify the data.

mydataset.tables["UserList"]. rows[0]["UserName"]= "flying brother";

This allows us to modify the username field in the first row of data.

Delete Data

Delete data, mainly using the Delete method provided by Rowscollection, see the following program is also very simple things:

mydataset.tables["UserList"],rows[0]. Delete ();

Mydataset.acceptchange ();//is important, but in Add (), Update (), when you want to place theoleadaper.update (), after

This line of data has been deleted.

Recovering data

Sometimes we get errors when we add/modify data, and then we need to restore the original data. The following program shows how to determine whether an error occurred:

if (mydataset.haserrors)
{
Mydataset.rejectchanges ();
}
 

First we check if there is an error in the dataset, and if so, restore the data in the dataset using the RejectChanges () method. Note that this recovery is the data in all the tables in the dataset and in the DataRow in the table, which means that the data in this cross-operation is all restored. If we only need to restore some of the content, we can use the DataTable or DataRow's RejectChanges (), which is not explained in detail, using the same method as a dataset, but the operation is different.

Detect if the dataset has changed

we are sending the dataset to the database to save it, and we need to see if the dataset has been altered. If there is no change, we will not need to modify the database.

if (mydataset.haschanges)
{
Save
}else{
Do not take any action
}

Update Database

The operations above are only for datasets, there is no database operation, but our goal is toSave the data to the data, so we need to call DataSetCommand's Update method here。 The following program shows how to hand data from a dataset to a database.

Mycomm.update (myDataSet);

A very simple sentence, hehe. It is important to note that ifa dataset contains multiple tables, and we only update one, then we have to specify the updated data table name:

mycomm.update (myDataSet, "userlist");

when the Update method is called, DataSetCommand compares the data in the database to the data in the dataset and updates it in a different place.

For the operation of the dataset, we only talk about so much here, in fact, there are many methods and properties of the dataset, the function is also very full, I think here now the function, the general operation is enough.

Use datasets to change data and save changes to the database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.