SqlDataAdapter. Update () method and SqlCommandBuilder, sqlcommandbuilder

Source: Internet
Author: User

SqlDataAdapter. Update () method and SqlCommandBuilder, sqlcommandbuilder

When using SqlDataAdapter to manipulate a dataset, the most common methods are Fill () and Update.

Fill () is filled with DataSet or able, and Update () is to Update the changes in DataSet or DataTable to the database. If the Update () method is not used, changes to data in DataSet or DataTable do not affect data in the database.

Example: Fill the able with SqlDataAdapter. Here the Employees table in the Northwind database is used.

String strcon1 = "Data Source =.; Initial Catalog = Northwind; Integrated Security = True ";

Using (SqlConnection conn = new SqlConnection (strcon1 ))

{

Conn. Open ();

String strsql = "select * from employees ";

SqlCommand cmd = new SqlCommand (strsql, conn );

Ad = new SqlDataAdapter ();

Ad. SelectCommand = cmd;

Dt = new DataTable ("employees ");

Ad. Fill (dt );

Ds = new DataSet ();

Ds. Tables. Add (dt );

This. dataGridView1.DataSource = ds. Tables [employees];

Add a record:

// Add a new row

DataRow newRow = dt. NewRow ();

NewRow ["EmployeeID"] = 11;

NewRow ["LastName"] = "Bill ";

NewRow ["FirstName"] = "Gata ";

Dt. Rows. Add (newRow );

Update: When Update is used, the system prompts you to have the InsertCommand of SqlDataAdapter. here we can use SqlCommandBuilder to automatically generate

// Use SqlCommandBuilder to automatically generate InsertCommand with Insert statements

SqlCommandBuilder cb = new SqlCommandBuilder (ad );

Ad. InsertCommand = cb. GetInsertCommand ();

// Update the data in DataSet to the database

Ad. Update (ds, "employees ");

}

 

 

 

 

From: http://blog.csdn.net/highplayer/article/details/6563238

Related Article

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.