Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
194
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

13

 

 

 

Using DataSets to Read Data

Topic Objective

To describe how to retrieve data from a database by using DataSets.

Lead-in

Now that we can establish a connection, we need to be able to execute statements against the database to retrieve data.

!Create the Database Connection

!Store the Query in a SqlDataAdapter

SqlDataAdapter mySqlDataAdapter = SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(

new SqlDataAdapter(

"select * from customers", mySqlConnection); "select * from customers", mySqlConnection);

! Create and Populate the DataSet with DataTables

DataSet myDataSet = new DataSet(); DataSet myDataSet = new DataSet();

mySqlDataAdapter.Fill(myDataSet,"Customers");

mySqlDataAdapter.Fill(myDataSet,"Customers");

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Delivery Tip

Explain the parameters to the Fill method. The second parameter is the name that will be given to the DataTable created in the DataSet. You use this name when reading data from the

DataSet.

After you establish a connection to a database, you can access its data.

ADO.NET provides multiple ways to access data.

Using DataSets

The DataSet object is the centerpiece of ADO.NET. It represents a complete set of data, including multiple, related tables, and constraints.

Although a DataSet stores data, you need DataAdapter objects to create and initialize the various tables. You also need the Fill method to populate a DataSet with the results from a query.

The Fill method takes two parameters: a DataSet instance and a string. The DataSet instance represents the DataSet to be filled, and the string identifies the DataTable that will be created inside the DataSet. A DataSet can contain many DataTables. You use the string supplied to the Fill method to reference the DataTable after it is created.

14

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

The following code example illustrates how to create a SqlDataAdapter object that contains the query statement. The Fill method then populates the DataSet with the results from the query.

//Create a connection SqlConnection mySqlConnection = new

SqlConnection("server=(local)\\NetSDK;! Trusted_Connection=yes;database=northwind");

//Create the DataAdapter

SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter( "select * from customers", mySqlConnection);

// Create and populate the DataSet DataSet myDataSet = new DataSet();

mySqlDataAdapter.Fill(myDataSet,"Customers");

Displaying Data In A DataSet

Because the data is stored in a collection of rows in the table, you can easily use a foreach statement to iterate through the rows:

foreach (DataRow myDataRow in myDataSet.Tables["Customers"].Rows)

{

Console.WriteLine(

" CustomerID: {0}", myDataRow["CustomerID"].ToString);

}

Typed DataSet

Along with late bound access to values through weakly typed variables, the DataSet provides access to data through a strongly typed metaphor. By using user-friendly names and strongly typed variables, you can access tables and columns that are part of the DataSet. You can also transport a strongly typed DataSet by using an XML Web service.

A typed DataSet is a class that derives from a DataSet. As such, it inherits all of the methods, events, and properties of a DataSet. Additionally, a typed DataSet provides strongly typed methods, events, and properties. This means that you can access tables and columns by name, instead of using collectionbased methods. Aside from the improved readability of the code, a typed DataSet also allows the Microsoft Visual Studio® .NET code editor to automatically complete lines as you type.

Additionally, a strongly typed DataSet provides access to the correct types for values at compile time. With a strongly typed DataSet, type mismatch errors are caught when the code is compiled rather than at run time.

Using an XML Schema that complies with the XML Schema definition language (XSD) standard, you can generate a strongly typed DataSet by using the XSD.exe tool that is provided with the .NET Framework SDK. The use of this tool is outside the scope of this module.

You will see how to easily create and use a typed DataSet using Visual Studio

.NET in this module’s lab.

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

15

 

 

 

Storing Multiple Tables in a DataSet

Topic Objective

To explain how to retrieve and store multiple tables in a DataSet.

Lead-in

Unlike a disconnected recordset, a DataSet can hold more than one table.

! Add the First Table

SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter( SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter( "select * from customers",mySqlConnection);

"select * from customers",mySqlConnection); DataSet myDataSet = new DataSet();

DataSet myDataSet = new DataSet(); mySqlDataAdapter.Fill(myDataSet,"Customers"); mySqlDataAdapter.Fill(myDataSet,"Customers");

! Add the Subsequent Table(s)

mySqlDataAdapter.SelectCommand.CommandText = mySqlDataAdapter.SelectCommand.CommandText =

"select * from orders"; "select * from orders";

mySqlDataAdapter.Fill(myDataSet,"Orders");

mySqlDataAdapter.Fill(myDataSet,"Orders");

DataSet: Customers

Orders

Data Tables

*****************************ILLEGAL FOR NON-TRAINER USE******************************

A DataSet can contain multiple tables. You can retrieve multiple tables from a database and store them in a DataSet.

Delivery Tip

Tell students that they can create new relationships between the tables in a

DataSet.

Note You can store tables from different databases in the same DataSet.

! To retrieve and store multiple tables in a DataSet

1. Create and populate the first DataSet.

DataSet myDataSet = new DataSet();

string strSql ="select * from customers"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter( strSql, mySqlConnection); mySqlDataAdapter.Fill(myDataSet,"Customers");

2.Reset the SelectCommand, InsertCommand, or DeleteCommand property of the DataAdapter object to a new command string.

strSql = "select * from orders"; mySqlDataAdapter.SelectCommand.CommandText = strSql;

3. Call Fill again. mySqlDataAdapter.Fill(myDataSet,"Orders");

16

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

The following code shows how you can add two tables from two different queries, one for authors and the other for titles, to the same DataSet.

// create connection to database string strConn = "server=(local)\\NetSDK;!

Trusted_Connection=yes;database=northwind";

SqlConnection mySqlConnection = new SqlConnection(strConn);

string strSql = "select * from customers" SqlDataAdapter mySqlDataAdapter =

new SqlDataAdapter(strSql, mySqlConnection); //fill DataSet with first set of data

DataSet myDataSet = new DataSet(); mySqlDataAdapter.Fill(myDataSet,"Customers"); //fill DataSet with first set of data

strSql = "select * from orders" mySqlDataAdapter.SelectCommand.CommandText = strSql; mySqlDataAdapter.Fill(myDataSet,"Orders");

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

17

 

 

 

Using DataViews

Topic Objective

To explain the role of DataViews in accessing data from a database by using DataSets.

Lead-in

To display data in a DataSet, you can use a

DataView.

!DataViews Can be Customized to Present a Subset of Data from a DataTable

!The DefaultView Property Returns the Default DataView for the Table

DataView myDataView =

DataView myDataView =

myDataSet.Tables["Customers"].DefaultView;

myDataSet.Tables["Customers"].DefaultView;

! Setting Up Different Views

myDataView.Sort = "Country"; myDataView.Sort = "Country";

myDataView.RowFilter = "Country = 'Argentina'"; myDataView.RowFilter = "Country = 'Argentina'";

*****************************ILLEGAL FOR NON-TRAINER USE******************************

There are many ways to filter data. One way is to filter data at the database command level, by using a where clause in your query. A second way is to filter the data after it is in the DataSet. This topic covers filtering in the

DataSet.

Filtering and Sorting with DataViews

To display the data held in a DataSet, you can use a DataView.

DataViews can be customized to present a subset of data from the DataTable. This capability allows you to have two controls bound to the same DataTable, but showing different versions of the data. For example, one control may be bound to a DataView that shows all the rows in the table, and a second may be configured to display only the rows that have been deleted from the DataTable.

Each DataTable in a DataSet has a DefaultView property, which returns the default view for the table. You can access the default DataView of a DataSet as follows:

DataView myDataView = myDataSet.Tables["Customers"].DefaultView;

Note The DataSet object contains a Tables collection. You reference the

DataTable you are interested in by name.

You can sort the data. For example, you can sort the customers by country.

myDataView.Sort = "Country";

18

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

Setting up a Different View of a DataSet

You can also create a view of a subset of the data in a DataTable. For example, you can set the RowFilter property on a DataView to retrieve only customers from Argentina.

myDataView.RowFilter = "Country = 'Argentina'";

For more information about the properties of the DataView object, see the Microsoft .NET Framework SDK documentation.

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

19

 

 

 

Updating a Database From a DataSet

Topic Objective

To show how to update data in a Database from a

DataSet.

Lead-in

This topic illustrates how to update data in a database using a DataSet. You can also insert, update, and delete data in a database directly using a SqlCommand as described in the .NET Framework SDK.

! SQLCommandBuilder generates Update command

SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder mySqlCommandBuilder = new

SqlCommandBuilder(mySqlDataAdapter);

SqlCommandBuilder(mySqlDataAdapter);

! Set the MissingSchemaAction property

mySqlDataAdapter.MissingSchemaAction = mySqlDataAdapter.MissingSchemaAction =

MissingSchemaAction.AddWithKey;

MissingSchemaAction.AddWithKey;

! Add a row

DataRow myDataRow =

DataRow myDataRow =

myDataSet.Tables["Customers"].NewRow();

myDataSet.Tables["Customers"].NewRow(); myDataRow["CustomerId"] = "NewID"; myDataRow["CustomerId"] = "NewID";

// ...

// ...

myDataSet.Tables["Customers"].Rows.Add(myDataRow);

myDataSet.Tables["Customers"].Rows.Add(myDataRow);

! To submit the data

mySqlDataAdapter.Update(myDataSet, "Customers"); mySqlDataAdapter.Update(myDataSet, "Customers");

*****************************ILLEGAL FOR NON-TRAINER USE******************************

This topic illustrates how to update data in a database by using a DataSet. You can also insert, update, and delete data in a database directly by using a SqlCommand as described in the .NET Framework SDK documentation.

After a DataSet is loaded, you can modify the data, and the DataSet will track the changes. The DataSet may be considered an in-memory cache of data that is retrieved from a database. In this topic, you will see how to use the Add method on the DataTable to add new data to a DataSet. The Add method takes either an array of the expected data columns, or a DataRow.

To load the DataSet from the database:

SqlConnection myConnection = new SqlConnection( "server=(local)\\NetSDK;! Trusted_Connection=yes;database=northwind");

SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter( "Select * from Customers",

myConnection);

DataSet myDataSet = new DataSet();

Before you can submit the update back to the database, you must set up the

InsertCommand, UpdateCommand, and DeleteCommand to reconcile the changes to the database. For limited scenarios you can use the SqlCommandBuilder to automatically generate those for you:

SqlCommandBuilder mySqlCommandBuilder = new

SqlCommandBuilder(mySqlDataAdapter);

20

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

Because Fill will not cause primary key and unique key information to be retrieved unless AddWithKey is specified, you must set the

MissingSchemaAction property to AddWithKey:

mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

mySqlDataAdapter.Fill(myDataSet, "Customers");

DataRow myDataRow;

myDataRow = myDataSet.Tables["Customers"].NewRow();

The DataTable must return a DataRow through the NewRow method. The method returns a DataRow object with the appropriate schema of the DataTable. The new DataRow is independent of the table until it is added to the RowsCollection.

myDataRow["CustomerId"] = "NewID";

myDataRow["ContactName"] = "New Name"; myDataRow["CompanyName"] = "New Company Name";

myDataSet.Tables["Customers"].Rows.Add(myDataRow);

To submit the data from the DataSet into the database, use the Update method on the SqlDataAdapter.

mySqlDataAdapter.Update(myDataSet, "Customers");

You can change data in a DataRow by accessing the DataRow. You can use the index of the row in the RowsCollection that is accessed through the Rows property:

myDataSet.Tables["Customers"].Rows[0]["ContactName"]="Peach";

You can also access a specific row by the primary key value:

DataRow myDataRow1 = myDataSet.Tables["Customers"].Rows.Find("ALFKI");

myDataRow1["ContactName"]="Peach";

In the preceding example, "ALFKI" is the value of the primary key "CustomerID" in the Customers table. When using the SqlDataAdapter, the key is established from the database. You can also set the key through the PrimaryKey property if you are not using the database.

Use the Delete method to remove the Row. Note that a logical deletion occurs in the DataSet, which only results in a hard deletion after the DataSet is updated to the database. Similarly, you can use RejectChanges on the DataSet, in which case the Row is restored.

myDataSet.Tables["Customers"].Rows[0].Delete();

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. Because original and new values are maintained, you can establish scenarios such as optimistic locking and key changes.

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

21

 

 

 

Demonstration: Accessing Data with DataSets

Topic Objective

To demonstrate how to open a database, create a DataSet with multiple tables, and create views on the data.

Lead-in

In this demonstration, you will see how to access data with a DataSet.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this demonstration, you will see how to access data with a DataSet.

Run the Visual Studio .NET Accessing Data with DataSets project from the following location:

<install folder>\Democode\Mod16\Demo16.1

The code reads in data from database tables, creates views, and updates the database.

Tip You can examine the database tables and stored procedures by using the

Server Explorer window Data Connections entries.

22

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

Running this program produces output that is similar to the following:

Opened Connection to! server=(local)\NetSDK;! Trusted_Connection=yes;database=northwind Total Number of Regions: 4

Total Number of Customers: 91

Regions:

ID: 1 Description: Eastern

ID: 2 Description: Western

ID: 3 Description: Northern

ID: 4 Description: Southern

First 5 Customer IDs:

Customer ID: ALFKI

Customer ID: ANATR

Customer ID: ANTON

Customer ID: AROUT

Customer ID: BERGS

View sorted by country

First 5 Customers in the view:

Customer ID: CACTU

Country: Argentina

Customer ID: OCEAN

Country: Argentina

Customer ID: RANCH

Country: Argentina

Customer ID: ERNSH

Country: Austria

Customer ID: PICCO

Country: Austria

Filtered by country equals Argentina

Customers with Country = Argentina, number of entries 3 ID: CACTU Country: Argentina

ID: OCEAN Country: Argentina

ID: RANCH Country: Argentina

Соседние файлы в папке c#