Update Dataset data back to Database
2012-11-01 17:00
471 查看
This post explains how to insert, update, and delete data in a Database using Dataset.
The DataSet can be considered an in-memory cache of data retrieved from a database. The DataSet consists of a collection of tables, relationships, and constraints.
Firstly, we have to fill data into a DataSet from Database.
Secondly, when the DataSet is loaded, you can modify the data, and the DataSet will keep track of the changes made bu user.
The Add method of DataTable accepts either an array of the expected data columns, or a DataRow.
(Please note that all code is in c# language)
Step 1: Create a new Connection and SqlDataAdapter
SqlConnection myConnection = new SqlConnection(“connectionStringGoesHere”);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(“Select * from tblNews”, myConnection);
DataSet myDataSet = new DataSet();
DataRow myDataRow;
Step 2: Create SqlCommandBuilder(The SqlDataAdapter does not automatically generate the Transact-SQL statements required to match changes made to a DataSet with SQL Server. But, you can create a SqlCommandBuilder object to automatically generate Transact-SQL statements for single-table updates.)
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
// Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
// key & unique key information to be retrieved unless AddWithKey is specified.
mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
mySqlDataAdapter.Fill(myDataSet, “tblNews”);
Step 3: Add rows to DataTable
myDataRow = myDataSet.Tables["tblNews"].NewRow();
myDataRow["cNewsId"] = “NewID”;
myDataRow["cHeading"] = “New Heading”;
myDataRow["cContent"] = “Content here”;
myDataSet.Tables["tblNews"].Rows.Add(myDataRow);
Step 4: Editing Row Data
We can change the data in a DataRow by accessing the DataRow. Use the index of the row in the RowsCollection accessed through the Rows property:
myDataSet.Tables["tblNews"].Rows[0]["cHeading"]=”Abc”;
Access a specific row by specifying the Primary Key value:
DataRow myDataRow1 = myDataSet.Tables["tblNews"].Rows.Find(“124″);
myDataRow1["cHeading"]=”Abc”;
Here “124″ is the value of the Primary Key “cHeading” in the “tblNews” table.
Step 5: Deleting a record
Use Delete method to delete a Row. All changes are done in dataset until you don’t explicitly update DataSet data to the Database. Use RejectChanges method of DataSet to reverse all changes made to DataSet.
myDataSet.Tables["tblNews"].Rows[0].Delete();
Note: The original and new values are maintained in the row. The RowChanging event allows you to access both original and new values to decide whether you want the edit to proceed.
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
Step 6: Finally Update DataBase
To submit the data from the DataSet into the database, use dataAdapter’s Update method.
mySqlDataAdapter.Update(myDataSet, “tblNews”);
A Visual Studio Solution code sample will be coming soon……
**End of article**
The DataSet can be considered an in-memory cache of data retrieved from a database. The DataSet consists of a collection of tables, relationships, and constraints.
Firstly, we have to fill data into a DataSet from Database.
Secondly, when the DataSet is loaded, you can modify the data, and the DataSet will keep track of the changes made bu user.
The Add method of DataTable accepts either an array of the expected data columns, or a DataRow.
(Please note that all code is in c# language)
Step 1: Create a new Connection and SqlDataAdapter
SqlConnection myConnection = new SqlConnection(“connectionStringGoesHere”);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(“Select * from tblNews”, myConnection);
DataSet myDataSet = new DataSet();
DataRow myDataRow;
Step 2: Create SqlCommandBuilder(The SqlDataAdapter does not automatically generate the Transact-SQL statements required to match changes made to a DataSet with SQL Server. But, you can create a SqlCommandBuilder object to automatically generate Transact-SQL statements for single-table updates.)
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
// Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
// key & unique key information to be retrieved unless AddWithKey is specified.
mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
mySqlDataAdapter.Fill(myDataSet, “tblNews”);
Step 3: Add rows to DataTable
myDataRow = myDataSet.Tables["tblNews"].NewRow();
myDataRow["cNewsId"] = “NewID”;
myDataRow["cHeading"] = “New Heading”;
myDataRow["cContent"] = “Content here”;
myDataSet.Tables["tblNews"].Rows.Add(myDataRow);
Step 4: Editing Row Data
We can change the data in a DataRow by accessing the DataRow. Use the index of the row in the RowsCollection accessed through the Rows property:
myDataSet.Tables["tblNews"].Rows[0]["cHeading"]=”Abc”;
Access a specific row by specifying the Primary Key value:
DataRow myDataRow1 = myDataSet.Tables["tblNews"].Rows.Find(“124″);
myDataRow1["cHeading"]=”Abc”;
Here “124″ is the value of the Primary Key “cHeading” in the “tblNews” table.
Step 5: Deleting a record
Use Delete method to delete a Row. All changes are done in dataset until you don’t explicitly update DataSet data to the Database. Use RejectChanges method of DataSet to reverse all changes made to DataSet.
myDataSet.Tables["tblNews"].Rows[0].Delete();
Note: The original and new values are maintained in the row. The RowChanging event allows you to access both original and new values to decide whether you want the edit to proceed.
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
Step 6: Finally Update DataBase
To submit the data from the DataSet into the database, use dataAdapter’s Update method.
mySqlDataAdapter.Update(myDataSet, “tblNews”);
A Visual Studio Solution code sample will be coming soon……
**End of article**
相关文章推荐
- Model First, Database First or Code First–Update to Data Points Column
- "Failed to update database "c:\inetpub\wwwroot\WebSite1\App_Data\ASPNETDB.MDF" because the database is read-only."的解决办法
- 解决:Failed to update database: "APP_DATA\ASPNETDB.MDF" is read-only .
- Use SqlDataAdapter to update database, but SqlCommandBuilder required
- "Failed to update database "c:\inetpub\wwwroot\WebSite1\App_Data\ASPNETDB.MDF" because the database is read-only."的解决办法
- Top 10 steps to optimize data access in SQL Server: Part IV (Diagnose database performance problems)
- Using v$datafile to track database growth
- [FAQ19780]How to auto update apn database by OTA
- How to Back Up and Restore a MySQL Database
- Spark 2.0 DataFrame map操作中Unable to find encoder for type stored in a Dataset.问题的分析与解决
- Spark 2.0 DataFrame map操作中Unable to find encoder for type stored in a Dataset.问题的分析与解决
- a universal class to complete import data from an excel file into a database
- 奇怪的SqlDataAdapter.Update(Dataset)问题....请高手进来帮忙搞定
- Top 10 steps to optimize data access in SQL Server: Part V (Optimize database files and apply partitioning)
- Pass data to CGI script and back with jQuery.ajax
- openssl TXT_DB error number 二 failed to update database
- Unable to resume activity : android.database.StaleDataException: Attempted to access a cursor after it has been closed. 异常
- Designing Data Storage Architecture- How to Sync Large SQL Server Databases to SQL Azure
- Database Systems: Introduction to Databases and Data Warehouses/Nenad Jukic-图书-亚马逊中国
- jface databinding:输入无效数值时强制恢复初始值-updateModelToTarget