Anda di halaman 1dari 9

United Kingdom Change | All Microsoft Sites

Help and Support


Top of Form

Bottom of Form

• Support Home

• Solution Centres

• Advanced Search

• Downloads

• Buy products
Article ID: 308507 - Last Review: July 14, 2004 - Revision: 3.4
How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visu
View products that this article applies to.

This article was previously published under Q308507

On This Page
Expand all | Collapse all
SUMMARY

This article contains Microsoft Visual C# .NET code samples that demonstrate how to use theSqlDataAdapter object to update a SQL Server d

that are run on a DataSet object that is populated with data from a table in the database.

Back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, skills and knowledge, and service packs that are requir

• Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows NT 4.0 Server

• Microsoft Visual Studio .NET

• Microsoft Visual C# .NET

• Microsoft SQL Server version 7.0 or later

This article assumes that you are familiar with the following topics:

• Visual C# .NET

• ADO.NET fundamentals and syntax

Back to the top

Description of the Technique

The SqlDataAdapter object serves as a bridge between an ADO.NET DataSet object and a SQL Server database. SqlDataAdapter is an interm

ADO.NETDataSet object with data that is retrieved from a SQL Server database, then updates the database to reflect the changes (such as inser

made to the data by using the DataSet object.

The InsertCommand, the UpdateCommand, and the DeleteCommand properties of theSqlDataAdapter object update the database with the

on aDataSet object. These properties are SqlCommand objects that specify the INSERT, the UPDATE, and the DELETE Transact-SQL comm

dataset modifications to the target database. The SqlCommand objects that are assigned to these properties can be created manually in code or

using theSqlCommandBuilder object.

The first code sample in this article demonstrates how to use the SqlCommandBuilder object to automatically generate the UpdateCommand

the SqlDataAdapter object. The second sample uses a scenario in which you cannot use automatic command generation. The second sample de

create and use a SqlCommand object as theUpdateCommand property of a SqlDataAdapter object.

Back to the top


Create the Sample SQL Server Table

To create a sample SQL Server table that you can use in the Visual C# .NET code samples that are documented in this article, follow these steps

1. Open SQL Query Analyzer, and then connect to the database in which you want to create the sample table. The code samples in this a
the Northwind database that is included with Microsoft SQL Server.

2. To create a sample table that is named CustTest and to insert a record into the table, run the following Transact-SQL statements:

3. Create Table CustTest


4. (
5. CustID int primary key,
6. CustName varchar(20)
7. )
8.
9. Insert into CustTest values(1,'John')

Back to the top

Code Sample 1: Automatically Generated Commands

If the SELECT statement that you use to retrieve the data that populates a DataSet is based on a single database table, you can use the Comman

automatically generate the DeleteCommand, the InsertCommand, and the UpdateCommand properties of theDataAdapter. This simplifies a

required to perform INSERT, UDPATE, and DELETE operations.

As a minimum requirement, you must set the SelectCommand property to automatically generate commands. The table schema that the SelectC

the syntax of the INSERT, the UPDATE, and the DELETE statements that are automatically generated.

The SelectCommand property must also return at least one primary key or unique column. If none are present, an InvalidOperation exception i

are not generated.

To create a sample Visual C# .NET console application that demonstrates how to use theSqlCommandBuilder object to automatically generate

theInsertCommand, and the UpdateCommand properties of the SqlCommand object for aSqlDataAdapter object, follow these steps:

1. To create a new Visual C# .NET console application, follow these steps:

a. Start Microsoft Visual Studio .NET.

b. On the File menu, point to New, and then click Project.

c. Click Visual C# Project under Project Types, and then click Console Application under Templates.
Replace the default contents of Class1 with the following code:

using System.Data;
using System.Data.SqlClient;
using System;
namespace Q308507 {

class Class1 {
static void Main(string[] args) {

SqlConnection cn = new SqlConnection();


DataSet CustomersDataSet = new DataSet();
SqlDataAdapter da;
SqlCommandBuilder cmdBuilder;

//Set the connection string of the SqlConnection object to connect


//to the SQL Server database in which you created the sample
//table.
cn.ConnectionString = "Server=server;Database=northwind;UID=login;PWD=password;";

cn.Open();

//Initialize the SqlDataAdapter object by specifying a Select command


//that retrieves data from the sample table.
da = new SqlDataAdapter("select * from CustTest order by CustId", cn);

//Initialize the SqlCommandBuilder object to automatically generate and initialize


//the UpdateCommand, InsertCommand, and DeleteCommand properties of the SqlDataAdapt
cmdBuilder = new SqlCommandBuilder(da);

//Populate the DataSet by running the Fill method of the SqlDataAdapter.


da.Fill(CustomersDataSet, "Customers");

//Display the Update, Insert, and Delete commands that were automatically generated
//by the SqlCommandBuilder object.
Console.WriteLine("Update command Generated by the Command Builder : ");
Console.WriteLine("==================================================");
Console.WriteLine(cmdBuilder.GetUpdateCommand().CommandText);
Console.WriteLine(" ");

Console.WriteLine("Insert command Generated by the Command Builder : ");


Console.WriteLine("==================================================");
Console.WriteLine(cmdBuilder.GetInsertCommand().CommandText);
Console.WriteLine(" ");

Console.WriteLine("Delete command Generated by the Command Builder : ");


Console.WriteLine("==================================================");
Console.WriteLine(cmdBuilder.GetDeleteCommand().CommandText);
Console.WriteLine(" ");

//Write out the value in the CustName field before updating the data using the DataS
Console.WriteLine("Customer Name before Update : " + CustomersDataSet.Tables["Custom
["CustName"]);

//Modify the value of the CustName field.


CustomersDataSet.Tables["Customers"].Rows[0]["CustName"] = "Jack";

//Post the data modification to the database.


da.Update(CustomersDataSet, "Customers");

Console.WriteLine("Customer Name updated successfully");

//Close the database connection.


cn.Close();

//Pause
Console.ReadLine();
}

}
Modify the connection string as appropriate for your environment.

Save and then run the application. Notice that a console window opens and then displays the following output:

Update command Generated by the Command Builder :


==================================================
UPDATE CustTest SET CustID = @p1 , CustName = @p2 WHERE ( CustID = @p3 AND CustName = @p4 )

Insert command Generated by the Command Builder :


==================================================
INSERT INTO CustTest( CustID , CustName ) VALUES ( @p1 , @p2 )

Delete command Generated by the Command Builder :


==================================================
DELETE FROM CustTest WHERE ( CustID = @p1 AND CustName = @p2 )

Customer Name before Update : John


Customer Name updated successfully

Press any key to dismiss the console window and to stop the application.

Back to the top

Code Sample 2: Manually Create and Initialize the UpdateCommand Property

The output that Code Sample 1 generates indicates that the logic to generate commands automatically for UPDATE statements is based on optim

records are not locked for editing, and other users or processes can modify records whenever.

Because a record can be modified after it is returned from the SELECT statement but before the UPDATE statement is issued, the UPDATE sta

generated contains a WHERE clause so that a row is updated only if it contains all of the original values. This is to avoid overwriting new data.

automatically generated tries to update a row that has been deleted or does not contain the original values that are found in theDataSet, the com

records, and a DBConcurrencyException exception is generated. To test this with the code in Code Sample 1, run the code in the Visual Studio

the DataSet has been filled but before the database is updated, and then delete the one row in the table from SQL Query Analyzer. The Update

If you want the UPDATE statement to complete regardless of original values, you must explicitly set the UpdateCommand for the DataAdapt

command generation.

To manually create and initialize the UpdateCommand property of the SqlDataAdapterobject that is used in Code Sample 1, follow these step
1. Replace the existing code in the Main function of Class1 in the Visual C# .NET console application that you created in the Code Sam
Commandssection with the following code:

2. SqlConnection cn = new SqlConnection();


3. DataSet CustomersDataSet = new DataSet();
4. SqlDataAdapter da;
5. SqlCommand DAUpdateCmd;
6.
7. cn.ConnectionString = "Server=server;Database=northwind;UID=login;PWD=password;"
8. cn.Open();
9.
10.da = new SqlDataAdapter("select * from CustTest order by CustId", cn);
11.
12.//Initialize the SqlCommand object that will be used as the UpdateCommand for th
13.
14.//Note that the WHERE clause uses only the CustId field to locate the record to
15.DAUpdateCmd = new SqlCommand("Update CustTest set CustName = @pCustName where Cu
da.SelectCommand.Connection);
16.
17.//Create and append the parameters for the Update command.
18.DAUpdateCmd.Parameters.Add(new SqlParameter("@pCustName", SqlDbType.VarChar));
19.DAUpdateCmd.Parameters["@pCustName"].SourceVersion = DataRowVersion.Current;
20.DAUpdateCmd.Parameters["@pCustName"].SourceColumn = "CustName";
21.
22.DAUpdateCmd.Parameters.Add(new SqlParameter("@pCustId", SqlDbType.Int));
23.DAUpdateCmd.Parameters["@pCustId"].SourceVersion = DataRowVersion.Original;
24.DAUpdateCmd.Parameters["@pCustId"].SourceColumn = "CustId";
25.
26.//Assign the SqlCommand to the UpdateCommand property of the SqlDataAdapter.
27.da.UpdateCommand = DAUpdateCmd;
28.da.Fill(CustomersDataSet, "Customers");
29.
30.Console.WriteLine("Customer Name before Update : " + CustomersDataSet.Tables["Cu
["CustName"]);
31.CustomersDataSet.Tables["Customers"].Rows[0]["CustName"] = "Jack";
32.da.Update(CustomersDataSet, "Customers");
33.
34.Console.WriteLine("Customer Name updated successfully");
35.
36.cn.Close();
37.Console.ReadLine();

38. Modify the connection string as appropriate for your environment.

39. Repeat steps 1 through 4 in the Code Sample 1: Automatically Generated Commandssection. Note that a DBConcurrencyException ex

Back to the top

APPLIES TO

• Microsoft ADO.NET 1.0

• Microsoft ADO.NET 1.1

• Microsoft Visual C# .NET 2002 Standard Edition

• Microsoft Visual C# .NET 2003 Standard Edition

Back to the top

Keywords: kbhowtomaster kbsqlclient kbsystemdata KB308507


Back to the top

Provide feedback on this information

Did this information solve your problem?

Yes

No

I don't know

Was this information relevant?

Yes

No
How much effort did you personally put forth to use this article?

Very low

Low

Moderate

Hig
h

Very high

What can we do to improve this information?

To protect your privacy, do not include contact information in your feedback.

Get Help Now


Contact a support professional by E-mail, Online, or Phone

Microsoft Support
Services Agreement
Contact Us | Terms of Use | Trademarks | Privacy Statement ©2010 Microsoft

Anda mungkin juga menyukai