Tải bản đầy đủ (.pdf) (7 trang)

Tài liệu Modifying Rows in a DataTable phần 1 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (34.49 KB, 7 trang )

Modifying Rows in a DataTable
In this section, you'll see the steps required to add, modify, and remove DataRow objects
from a DataTable and then push those changes to the database. The examples in this
section show how to add, modify, and delete rows in the Customers database table.

Note You'll find a complete program named AddModifyAndRemoveDataRows.cs in the
ch11 directory that illustrates the use of the methods shown in this section. This
program listing is omitted from this book for brevity.
Setting up a DataAdapter to Push Changes to the Database
In Chapter 10
, you saw that before you call the Fill() method of your DataAdapter to read
rows from the database, you first need to set the SelectCommand property of your
DataAdapter. For example:
SqlCommand mySelectCommand = mySqlConnection.CreateCommand();
mySelectCommand.CommandText =
"SELECT CustomerID, CompanyName, Address " +
"FROM Customers " +
"ORDER BY CustomerID";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySelectCommand;
The SELECT statement is then run when you call the mySqlDataAdapter object's Fill()
method to retrieve rows from the Customers table into a DataSet.
Similarly, before you can push changes to the database, you must first set up your
DataAdapter with Command objects containing appropriate SQL INSERT, UPDATE,
and DELETE statements. You store these Command objects in your DataAdapter object's
InsertCommand, UpdateCommand, and DeleteCommand properties.
You push changes from your DataSet to the database using the Update() method of your
DataAdapter. When you add, modify, or remove DataRow objects from your DataSet and
then call the Update() method of your DataAdapter, the appropriate InsertCommand,
UpdateCommand, or DeleteCommand is run to push your changes to the database.
Let's take a look at how to set the InsertCommand, UpdateCommand, and


DeleteCommand properties of a DataAdapter.
Setting the InsertCommand Property of a DataAdapter
The following example creates a SqlCommand object named myInsertCommand that
contains an INSERT statement:
SqlCommand myInsertCommand = mySqlConnection.CreateCommand();
myInsertCommand.CommandText =
"INSERT INTO Customers (" +
" CustomerID, CompanyName, Address" +
") VALUES (" +
" @CustomerID, @CompanyName, @Address" +
")";
myInsertCommand.Parameters.Add("@CustomerID", SqlDbType.NChar,
5, "CustomerID");
myInsertCommand.Parameters.Add("@CompanyName", SqlDbType.NVarChar,
40, "CompanyName");
myInsertCommand.Parameters.Add("@Address", SqlDbType.NVarChar,
60, "Address");
The four parameters to the Add() method are as follows:

The name of the parameter

The .NET type of the parameter

The maximum length of the string that may be assigned to the parameter's value

The name of the corresponding database column that the parameter is bound to

Note Commands and parameters are covered in Chapter 8, "Executing Database
Commands."
As you can see from the previous code, the @CustomerID, @CompanyName, and

@Address parameters are bound to the CustomerID, CompanyName, and Address
columns in the database.
Next, the following example sets the InsertCommand property of mySqlDataAdapter to
myInsertCommand:
mySqlDataAdapter.InsertCommand = myInsertCommand;
Setting the UpdateCommand Property of a DataAdapter
The following example creates a SqlCommand object named myUpdateCommand that
contains an UPDATE statement and sets the UpdateCommand property of
mySqlDataAdapter to myUpdateCommand:
myUpdateCommand.CommandText =
"UPDATE Customers " +
"SET " +
" CompanyName = @NewCompanyName, " +
" Address = @NewAddress " +
"WHERE CustomerID = @OldCustomerID " +
"AND CompanyName = @OldCompanyName " +
"AND Address = @OldAddress";
myUpdateCommand.Parameters.Add("@NewCompanyName", SqlDbType.NVarChar,
40, "CompanyName");
myUpdateCommand.Parameters.Add("@NewAddress", SqlDbType.NVarChar,
60, "Address");
myUpdateCommand.Parameters.Add("@OldCustomerID", SqlDbType.NChar,
5, "CustomerID");
myUpdateCommand.Parameters.Add("@OldCompanyName", SqlDbType.NVarChar,
40, "CompanyName");
myUpdateCommand.Parameters.Add("@OldAddress", SqlDbType.NVarChar,
60, "Address");
myUpdateCommand.Parameters["@OldCustomerID"].SourceVersion =
DataRowVersion.Original;
myUpdateCommand.Parameters["@OldCompanyName"].SourceVersion =

DataRowVersion.Original;
myUpdateCommand.Parameters["@OldAddress"].SourceVersion =
DataRowVersion.Original;
mySqlDataAdapter.UpdateCommand = myUpdateCommand;
There are two things to notice about this code:

The UPDATE statement's WHERE clause specifies parameters for CompanyID,
CompanyName, and Address columns. This uses optimistic concurrency, which
you'll learn about shortly.

A property named SourceVersion for the @OldCustomerID, @OldCompanyName
and @OldAddress parameters is set to DataRowVersion.Original. This causes the
values for these parameters to be set to the original DataRow column values
before you change them.
These items determine the concurrency of the UPDATE, which you'll now learn about.
Concurrency
Concurrency determines how multiple users' modifications to the same row are handled.
There are two types of concurrency that apply to a DataSet:

Optimistic Concurrency With optimistic concurrency, you can modify a row in a
database table only if no one else has modified that same row since you loaded it
into your DataSet. This is typically the best type of concurrency to use because
you don't want to overwrite someone else's changes.

"Last One Wins" Concurrency With "last one wins" concurrency, you can
always modify a row-and your changes overwrite anyone else's changes. You
typically want to avoid using "last one wins" concurrency.
To use optimistic concurrency, you have to do the following in your UPDATE or
DELETE statement's WHERE clause:
1. Include all the columns used in the original SELECT.

2. Set these column values to original values retrieved from the row in the table
before you changed the values.
When you do these two things in your UPDATE or DELETE statement's WHERE
clause, your statement first checks that the original row still exists before updating or
deleting the row. That way, you can be sure your changes don't overwrite anyone else's
changes. Of course, if the original row has been deleted by another user, then your
UPDATE or DELETE statement will fail.
To use "last one wins" concurrency, you just include the primary key and its value in the
WHERE clause of your UPDATE or DELETE statement. Since your UPDATE statement
doesn't check the original values, it simply overwrites anyone else's changes if the row
still exists. Also, a DELETE statement simply deletes the row-even if another user has
modified the row.
Returning to the previous code example that set the UpdateCommand property of
mySqlDataAdapter, you can see that all the columns are included in the WHERE clause
of the UPDATE. That satisfies the first requirement of using optimistic concurrency
shown earlier.
The second requirement is that you set the column in the WHERE clause to the original
row values. You do this by setting the SourceVersion property of the @OldCustomerID,
@OldCompanyName, and @OldAddress parameters to DataRowVersion.Original. At
runtime, this pulls the original values from the DataColumn objects in the DataRow
before you changed them and puts them in the UPDATE statement's WHERE clause.
Original is just one of the members of the System.Data.DataRowVersion enumeration;
the others are shown in Table 11.9
.
Table 11.9: DataRowVersion ENUMERATION MEMBERS
CONSTANT DESCRIPTION
Current The current column value.
Default The default column value.
Original The original column value.
Table 11.9: DataRowVersion ENUMERATION MEMBERS

CONSTANT DESCRIPTION
Proposed The proposed column value, which is set when you edit a DataRow using
the BeginEdit() method.
Setting the DeleteCommand Property of a DataAdapter
The following example creates a SqlCommand object named myDeleteCommand that
contains a DELETE statement and sets the DeleteCommand property of
mySqlDataAdapter to myDeleteCommand:
SqlCommand myDeleteCommand = mySqlConnection.CreateCommand();
myDeleteCommand.CommandText =
"DELETE FROM Customers " +
"WHERE CustomerID = @OldCustomerID " +
"AND CompanyName = @OldCompanyName " +
"AND Address = @OldAddress";
myDeleteCommand.Parameters.Add("@OldCustomerID", SqlDbType.NChar,
5, "CustomerID");
myDeleteCommand.Parameters.Add("@OldCompanyName", SqlDbType.NVarChar,
40, "CompanyName");
myDeleteCommand.Parameters.Add("@OldAddress", SqlDbType.NVarChar,
60, "Address");
myDeleteCommand.Parameters["@OldCustomerID"].SourceVersion =
DataRowVersion.Original;
myDeleteCommand.Parameters["@OldCompanyName"].SourceVersion =
DataRowVersion.Original;
myDeleteCommand.Parameters["@OldAddress"].SourceVersion =
DataRowVersion.Original;
mySqlDataAdapter.DeleteCommand = myDeleteCommand;
Notice that the DELETE statement also uses optimistic concurrency.
This completes the setup of the DataAdapter object.
Adding a DataRow to a DataTable
In this section, you'll learn how to add a DataRow to a DataTable. Before you see this,

let's populate a DataSet with the rows from the Customers table. The following code
creates a DataSet object named myDataSet and populates it by calling
mySqlDataAdapter.Fill():

×