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

Module 16 (Optional):

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 (1.02 MB, 64 trang )










Contents
Overview 1
Overview of ADO.NET 2
Connecting to a Data Source 10
Accessing Data with DataSets 12
Using Stored Procedures 26
Lab 16: Using ADO.NET to Access Data 34
Accessing Data with DataReaders 42
Binding to XML Data 50
Review 56

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



Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,


logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

 2001-2002 Microsoft Corporation. All rights reserved.

Microsoft, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint,
Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and
Window NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.


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


Instructor Notes
This module focuses on using ADO.NET to access data from various data
sources.
After completing this module, students will be able to:
!

Describe the ADO.NET object model.
!
Connect to a data source by using ADO.NET.
!
Retrieve data from a database by using DataReaders and DataSets.
!
Display the data from a database on the client by using DataGrid controls.
!
Use stored procedures to read data from a data source.
!
Read data from an XML file into DataSets.

Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need the Microsoft
®
PowerPoint
®
file 2349B_16.ppt.
Preparation Tasks
To prepare for this module, you should:
!
Read all of the materials for this module.
!
Complete all of the demonstrations.
!
Complete the lab.
!

Go through the animation.

Presentation:
120 Minutes

Lab:
60 Minutes
iv Module 16 (Optional): Using Microsoft ADO.NET to Access Data


Multimedia Presentation
This section provides multimedia presentation procedures that do not fit in the
margin notes or are not appropriate for the student notes.
Using ADO.NET to Access Data
!
To present the animation
Action Say this

Start animation There are two ways to access data from a database by using
ADO.NET: by using a DataSet or by using a DataReader.
This animation demonstrates how these two methods work
and highlights their differences.
Click Start
Click DataSet The DataSet method is a disconnected way to access data
from a database.
In this method, when a user requests data from a database, the
DataAdapter object is used to create a DataSet, which is
basically a collection of data tables from the database that
also retains the relationships between these tables. Notice
that, after a DataSet is populated, it is disconnected from the

database.
To display the data from the DataSet, you set up a DataView
for the desired table. The DataView is then bound to a list-
bound control for displaying purposes. You can use any of
the three list-bound controls, DataGrid, Repeater, or
DataList, to display data.
The data in the list-bound control is then displayed on the
client.
An important point to make here is that the use of a
DataView to display data is necessary only in ASP.NET
Beta 1. From the Beta 2 version onward, you can directly
bind the DataSet to a list-bound control.
Click DataReader This method is similar to the Microsoft ActiveX
®
Data
Objects (ADO) way of accessing data by using recordsets.
In this method, when a user requests data from a database, the
Command object retrieves the data into a DataReader. A
DataReader is a read-only/forward-only view of the data. A
DataReader works similarly to a Recordset in ADO,
allowing you to simply loop through the records. Like the
ADO Recordset, the DataReader is connected to the
database. You must explicitly close the connection when you
are finished reading data.

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


Module Strategy
Use the following strategy to present this module:

!
Overview of ADO.NET
This section provides students with an overview of ADO.NET. The section
begins a description of the objects used when connecting to a database both
with a DataReader and a DataSet. Point out to students that there are
Microsoft SQL Server

and ADO versions of many of these objects. After
describing the process of accessing data through a DataReader and a
DataSet, show the animation. Because students may be familiar with ADO,
this may be an ideal time to discuss some of the main differences between
ADO and ADO.NET.
When talking about using namespaces, explain their significance to the
students.
!
Connecting to a Data Source
From this point onward, students will actually start working with
ADO.NET. Tell them that all of the examples in this module use
SqlConnection objects rather than OleDbConnection objects. Direct the
students to the Microsoft .NET Framework software development kit (SDK)
documentation for more information.
!
Accessing Data with DataSets
ADO.NET provides two ways to access data, the DataSet and the
DataReader. This section focuses on accessing data by using the DataSet.
The DataSet represents a new concept, so spend additional time on this
section. The demonstrations actually show every aspect of data access with
ADO.NET. Go through the demonstrations carefully, and make sure that the
students understand the details.
!

Using Stored Procedures
Most students who have worked with a SQL Server database and ADO will
have experience with using stored procedures. This section provides the
students with information about how to use stored procedures and
parameterized stored procedures with ADO.NET.
!
Lab16: Using ADO.NET to Access Data
The lab for this module is encountered in the middle of the module. This is
because the module is long and also because the lab does not use material
from the last two sections in the module.
vi Module 16 (Optional): Using Microsoft ADO.NET to Access Data


!
Accessing Data with DataReaders
This section focuses on accessing data by using a DataReader. Point out to
the students that, when they use a DataReader, the database connection is
always open. When they are finished reading data, they must explicitly close
the connection.
!
Binding to XML Data
XML is fast emerging as the most popular language for exchanging data.
This section provides students with information on how to read XML data
by using ADO.NET.
Most students will already know about XML documents. However, for
students who are not familiar with XML, it will be useful to show an
example of an XML document and how it is displayed on the client.

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



Overview
!
Overview of ADO.NET
!
Connecting to a Data Source
!
Accessing Data with DataSets
!
Using Stored Procedures
!
Accessing Data with DataReaders
!
Binding to XML Data

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
ADO.NET, offers a rich suite of data handling and data binding functions for
manipulating all types of data. ADO.NET is an evolution of the ADO data
access model that directly addresses user requirements for developing scalable
applications. It was designed specifically for the Web with scalability,
statelessness, and XML in mind.

After completing this module, you will be able to:
!
Describe the ADO.NET object model.
!

Connect to a data source by using ADO.NET.
!
Retrieve data from a database by using DataReaders and DataSets.
!
Display the data from a database on the client by DataGrid controls.
!
Use stored procedures.
!
Read data from an XML file into DataSets.

Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
about the data binding
features in ASP.NET.
2 Module 16 (Optional): Using Microsoft ADO.NET to Access Data


"
""
" Overview of ADO.NET
!
The ADO.NET Object Model
!
RecordSets vs. DataSets
!
Using Namespaces


*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
ADO.NET is not a revision of Microsoft
®
ActiveX
®
Data Objects (ADO), but a
new way to manipulate data that is based on disconnected data and XML.
Although ADO is an important data access tool it is connected by default, relies
on an OLE DB provider to access data, and it is entirely Component Object
Model (COM)-based.
ADO.NET has been designed to work with disconnected datasets. Disconnected
datasets reduce network traffic.
ADO.NET uses XML as the universal transmission format. This guarantees
interoperability as long as the receiving component runs on a platform where an
XML parser is available. When the transmission occurs through XML, it is no
longer necessary that the receiver be a COM object. The receiving component
has no architectural restrictions whatsoever. Any software component can share
ADO.NET data, as long as it uses the same XML schema for the format of the
transmitted data.
In this section, you will learn about ADO.NET. You will learn about the new
and modified objects in ADO.NET. You will also learn about some of the new
namespaces.
Topic Objective
To introduce the topics
included in this section.

Lead-in
ASP.NET offers a new
means to retrieve data with
the introduction of
ADO.NET.
Module 16 (Optional): Using Microsoft ADO.NET to Access Data 3


The ADO.NET Object Model
DataAdapter
Connection
Database
Database
Command
.ASPX Page
List-Bound
Control
List-Bound
Control
DataReader
Company:
Northwind Traders
Company:
Northwind Traders
.ASPX Page
DataView
DataView
DataSet

*****************************

ILLEGAL FOR NON
-
TRAINER USE
******************************
ADO.NET evolved from the ADO data access model. By using ADO.NET, you
can develop applications that are robust and scalable, and that can use XML.
ADO.NET has some of the same objects as ADO (like the Connection and
Command objects), and introduces new objects, such as the Dataset,
DataReader, and DataAdapter.
Connection Objects
Connection objects are used to talk to databases. They have properties, such as
DataSource, UserID, and Password, which are needed to access a particular
DataSource. Commands travel over connections, and result sets are returned in
the form of streams that can be read by DataReaders or pushed into DataSet
objects.
There are two kinds of connection objects in ADO.NET: SqlConnection and
OleDbConnection.
Command Objects
Command objects contain the information that is submitted to a database. A
command can be a stored procedure call, an update statement, or a statement
that returns results. You can also use input and output parameters and return
values. In ADO.NET, you can use two kinds of command objects:
SqlCommand and OleDbCommand.
Topic Objective
To describe the ADO.NET
object model.
Lead-in
ADO.NET includes some of
the same objects as ADO
(like

Connection
and
Command
), and introduces
new objects, such as
DataSets
,
DataReaders

and
DataAdapters
.
Delivery Tip
Point out that there are ADO
and SQL Server versions of
the
Connection
,
Command
,
DataAdapter
,
and
DataReader
objects.
4 Module 16 (Optional): Using Microsoft ADO.NET to Access Data


DataReader Objects
A DataReader is somewhat synonymous with a read-only/forward-only view

of the data. The DataReader API supports flat as well as hierarchical data. A
DataReader object is returned after executing a command against a database. It
works similarly to a recordset in ADO; however the format of the returned
DataReader object is different from a recordset. For example, you may use the
DataReader to show the results of a search list in a Web page.

ADO.NET includes two types of DataReader objects: the SqlDataReader for
Microsoft SQL Server

version 7.0 (or later) data, and the OleDbDataReader
for ADO data. The DataReader object is database-specific. The behavior of the
SqlDataReader may differ from the behavior of the OleDbDataReader and
additional DataReader objects that are introduced in the future.
You use the OleDbCommand and SqlCommand objects and the
ExecuteReader method to transfer data into a DataReader.
DataSet Objects
The DataSet object is similar to the ADO Recordset object, but more
powerful, and with one other important distinction: the DataSet is always
disconnected
.
The DataSet provides a rich object model to work with when
passing data between various components of an enterprise solution. The
DataSet object represents a cache of data, with database-like behavior. It
contains tables, columns, relationships, constraints, and data. Data coming from
a database, an XML file, code, or user input can be entered into DataSet objects
and converted into files, forms, or databases. The behavior of a DataSet is
completely consistent regardless of the underlying database, SQL Server or
OLE DB. As changes are made to the DataSet, they are tracked in a way
similar to the way changes are tracked in a word processing document.
The DataSet object has a collection of DataTable objects. A DataTable

represents one table of in-memory data. It contains a collection of columns that
represents the table's schema. A DataTable also contains a collection of rows,
representing the data contained in the table.
You use the OleDbDataAdapter and SqlDataAdapter objects and the Fill
method to get data into a DataSet.
DataView Objects
A DataView enables you to create different views of the data stored in a
DataTable, a capability that is often used in data-binding applications. By
using a DataView, you can expose the data in a table with different sort orders,
and you can filter the data by row state or based on a filter expression.
A DataView provides a dynamic view of data whose content, ordering, and
membership reflect changes to the underlying DataTable as they occur. This is
different from the Select method of the DataTable, which returns a DataRow
array from a table per a particular filter and/or sort order, and whose content
reflects changes to the underlying table, but whose membership and ordering
remain static. The dynamic capabilities of the DataView make it ideal for data-
binding applications.
Module 16 (Optional): Using Microsoft ADO.NET to Access Data 5


DataAdapter Object
While the DataSet object provides a tool for in-memory data storage, you need
another tool to create and initialize the various tables. This tool is the
DataAdapter object. It represents a centralized console that hides the details of
working with connections and commands. The DataAdapter object allows for
the retrieval and saving of data between a DataSet object and the source data
store. It is responsible for pulling out data from the physical store and pushing it
into data tables and relations. The DataAdapter object is also responsible for
transmitting any update, insertion, or deletion to the physical database. You can
use four command objects to make any updates: UpdateCommand,

InsertCommand, DeleteCommand, and SelectCommand.
The DataAdapter object exists in two forms: SqlDataAdapter objects and
OleDbDataAdapter objects. The data source is SQL Server for
SqlDataAdapter objects and any other OLE DB provider for
OleDbDataAdapter objects.
The following illustration shows the use of a SQLDataAdapter object to
transfer data between a SQL Server database and a DataSet object.

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


Multimedia: Using ADO.NET to Access Data

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In this animation, you will learn how to access data by using ADO.NET and
how you can display that data in an ASP.NET page. To view the animation,
open the file 2349B_16A001.htm file from the Media folder.
Topic Objective
To provide a high-level
overview of how to access
data by using ADO.NET.
Lead-in
In this animation, you will
learn about how ADO.NET
accesses data and how you
can display that data in an

ASP.NET page.
Delivery Tip
Tell students that they can
view the animation again
later for themselves by
opening the
2349B_mod3.htm file from
the Media folder.

For details about how to run
and describe the animation,
see the Multimedia
Presentation section in the
Instructor Notes for this
module.
Module 16 (Optional): Using Microsoft ADO.NET to Access Data 7


Recordsets vs. DataSets
Transmit XML fileCOM marshallingTransmitting data
DisconnectedConnected or
disconnected
Data connections
Navigate via
relationships
Move row-by-rowMoving through data
Includes relationshipsBased on joinRelationships
Multiple tablesOne tableNumber of tables
DataSetRecordsetFeature


*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In ADO, the in-memory representation of database data is the recordset. In
ADO.NET, it is the DataSet. The DataSet contains a collection of tables and
knowledge of relationships between those tables. Each table contains a
collection of columns. These objects represent the schema of the DataSet. Each
table can then have multiple rows, representing the data held by the DataSet.
These rows track their original state along with their current state, so that the
DataSet tracks what kinds of changes have occurred. Additionally, the DataSet
provides persistence and de-persistence through XML.
There are important differences between recordsets and DataSets, which are
highlighted in the following table and detailed in the text that follows.
Feature Recordset DataSet

Number of tables One table Multiple tables
Relationships Based on join Includes relationships
Moving through data Move row-by-row Navigate via relationships
Data connections Connected or disconnected Disconnected
Transmitting data COM marshalling Transmit XML file

Number of Tables
An ADO recordset looks like a single table. If a recordset is to contain data
from multiple database tables, it must use a JOIN query, which assembles the
data from the various database tables into a single result table.
In contrast, an ADO.NET DataSet is a collection of one or more tables. The
tables within a data set are called data tables; specifically, they are DataTable
objects.

Topic Objective
To highlight the differences
between DataSets and
Recordsets.
Lead-in
In ADO, you used
Recordsets.
8 Module 16 (Optional): Using Microsoft ADO.NET to Access Data


Relationships
Typically, a DataSet also contains relationships. A relationship within a
DataSet is analogous to a foreign-key relationship in a database. In ADO.NET,
a DataRelation represents the relationship.
Moving Through Data
In ADO.NET, the methods you use to read or modify data differ from the
programming methods you use in ADO in the following ways:
!
In ADO, you scan sequentially through the rows of the recordset.
!
In ADO.NET, rows are represented as collections, so you can loop through
a table as you would through any collection or access particular rows
through ordinal or primary key index. DataRelation objects maintain
information about master and detail records and provide a method that
allows you to get records related to the one you are working with. For
example, starting from the row of the Investor table for "Jose Lugo", you
can navigate to the set of rows of the Purchase table that describes the
purchases made by Jose Lugo.

Data Connections

In ADO.NET, the DataSet provides disconnected access to database data. In
ADO, the recordset can provide disconnected access, but is typically used to
provide connected access.
Transmitting Data
To transmit an ADO disconnected recordset from one component to another,
you use COM marshalling. To transmit an ADO.NET data set, you simply
transmit an XML file. Because components exchange ADO.NET datasets by
using XML, firewalls can allow datasets to pass.
Module 16 (Optional): Using Microsoft ADO.NET to Access Data 9


Using Namespaces
!
Namespaces Used with ADO.NET Include:
#
System.Data
#
System.Data.OleDb
#
System.Data.SqlClient
#
System.Data.SqlTypes

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
The Microsoft .NET Framework is an object-oriented system. When using
specific parts of the framework, you must include references to the appropriate

namespace.
When using ADO.NET from either Microsoft Visual Basic
®
or Microsoft
Visual

C#

, you must reference the System.Data namespace, plus either the
System.Data.OleDb or System.Data.SqlClient namespace, depending on the
data source you choose to use. System.Data provides the code facilities, while
System.Data.OleDb and System.Data.SqlClient are the namespaces for the
two managed providers. The System.Data.Common namespace contains
classes that are shared by the .NET data providers. The System.Data.SqlTypes
namespace provides classes for native data types within SQL Server. These
classes provide a safer, faster alternative to other data types.
The following table summarizes the list of available namespaces with
ADO.NET.
Namespace Contains

System.Data Base objects and types for ADO.NET
System.Data.OleDb Managed OLE DB data store objects
System.Data.SqlClient SQL Server specific implementations of ADO.NET objects
System.Data.Common Classes shared by the .NET data providers
System.Data.SqlTypes SQL data types

Topic Objective
To describe the new
namespaces used with
ADO.NET.

Lead-in
In.NET, you must specify
the namespace that you
want to use.
10 Module 16 (Optional): Using Microsoft ADO.NET to Access Data


Connecting to a Data Source
!
Using SqlConnection
!
Using OleDbConnection
SqlConnection mySqlConnection = new
SqlConnection("server=(local)\\NetSDK;!
Trusted_Connection=yes;database=northwind");
SqlConnection mySqlConnection = new
SqlConnection("server=(local)\\NetSDK;!
Trusted_Connection=yes;database=northwind");
OleDbConnection myOleDbConnection = new
OleDbConnection("server=(local)\\NetSDK; !
Trusted_Connection=yes;database=northwind; !
provider=sqloledb");
OleDbConnection myOleDbConnection = new
OleDbConnection("server=(local)\\NetSDK; !
Trusted_Connection=yes;database=northwind; !
provider=sqloledb");

*****************************
ILLEGAL FOR NON
-

TRAINER USE
******************************
When you connect to a database, there are two routes that you can take: use
OLE DB or use the native SQL provider. The native SQL provider is faster, but
you must use Microsoft SQL Server as your database. If you are using
Microsoft Access, Microsoft Excel, a comma-delimited file, or some other data
source, you must use the OLE DB provider. You can use the OLE DB provider
with a Microsoft SQL Server database; however, it is not as fast as using the
native SQL provider.
The Connection object defines how to connect to a specific data store. The
.NET Framework provides two Connection objects: SqlConnection and
OleDbConnection. The SqlConnection object defines how to connect to
SQL Server databases and the OleDbConnection object allows you to establish
a connection to a database through an OLE DB provider.
Using SqlConnection
The following code illustrates how to create and open a connection to a
Microsoft SQL Server database by using the SqlConnection object.
SqlConnection mySqlConnection = new
SqlConnection("server=(local)\\NetSDK;!
Trusted_Connection=yes;database=northwind");


Embedded usernames/passwords in database connection strings are
inherently unsecure, and should only be used on platforms, such as Microsoft
Windows
®
9x, that do not support Integrated Security.
For more information about Integrated Security, see the .NET Framework SDK
documentation.


Topic Objective
To describe how to connect
to a data source by using
ADO.NET.
Lead-in
Connecting to a data source
is the first step in data
access.
Delivery Tip
Point out to students that in
ADO.NET you do not
always need to explicitly
open and close the
connection to the database.
Warning
Module 16 (Optional): Using Microsoft ADO.NET to Access Data 11


Using OleDbConnection
For the OLE DB Managed Provider, the connection string format is quite
similar to the connection string format used in OLE DB.
The following code illustrates how to create and open a connection to a
Microsoft SQL Server database by using OleDbConnection.
OleDbConnection myOleDbConnection = new
OleDbConnection("server=(local)\\NetSDK;!
Trusted_Connection=yes;database=northwind;!
provider=sqloledb");

The examples in this module, use SqlConnection objects. Implementation is
slightly different for using OleDbConnection objects. For more information

about using OleDbConnection objects, search for OleDbConnection in the
Microsoft .NET Framework SDK documentation.
Choosing a .NET Data Provider
Depending on the design and data source for your application, your choice of
.NET data provider can improve the performance, capability, and integrity of
your application. The following table discusses the advantages and limitations
of each .NET data provider.
Provider Notes

SQL Server
.NET Data Provider
Recommended for middle-tier applications that use Microsoft
SQL Server 7.0 or later.
Recommended for single-tier applications that use Microsoft
Data Engine (MSDE) or Microsoft SQL Server 7.0 or later.
Recommended over use of the OLE DB Provider for
SQL Server (SQLOLEDB) with the OLE DB .NET Data
Provider.
For Microsoft SQL Server version 6.5 and earlier, you must
use the OLE DB Provider for SQL Server with the OLE DB
.NET Data Provider.
OLE DB .NET
Data Provider
Recommended for middle-tier applications that use Microsoft
SQL Server 6.5 or earlier, or any OLE DB provider that
supports the OLE DB interfaces listed in OLE DB Interfaces
Used by the OLE DB .NET Data Provider (OLE DB 2.5
interfaces are not required).
For Microsoft SQL Server 7.0 or later, the SQL Server .NET
Data Provider is recommended.

Recommended for single-tier applications that use Microsoft
Access databases. Use of a Microsoft Access database for a
middle-tier application is not recommended.
Support for the OLE DB Provider for ODBC (MSDASQL) is
disabled. For access to Open Database Connectivity (ODBC)
data sources, an ODBC .NET Data Provider is available as a
separate download at

Delivery Tip
Stress to students that all
examples in the module and
lab will use SqlConnection
objects.
12 Module 16 (Optional): Using Microsoft ADO.NET to Access Data


"
""
"

Accessing Data with DataSets
!
Using DataSets to Read Data
!
Storing Multiple Tables in a DataSet
!
Using DataViews
!
Updating a Database from a DataSet
!

Displaying Data in the DataGrid Control

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
ADO.NET provides two ways to access data, DataSets and DataReaders.
In this section, you will learn how to access data by using DataSets. You will
also learn about DataViews and displaying data in DataGrid controls.
Topic Objective
To introduce the topics
included in the section.
Lead-in
After connecting to a
database, the next step is to
access data from it.
Module 16 (Optional): Using Microsoft ADO.NET to Access Data 13


Using DataSets to Read Data
!
Create the Database Connection
!
Store the Query in a SqlDataAdapter
!
Create and Populate the DataSet with DataTables
SqlDataAdapter mySqlDataAdapter =
new SqlDataAdapter(
"select * from customers", mySqlConnection);

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

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
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.
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.
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.
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 collection-
based 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
!
Add the First Table
!
Add the Subsequent Table(s)
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(
"select * from customers",mySqlConnection);
DataSet myDataSet = new DataSet();
mySqlDataAdapter.Fill(myDataSet,"Customers");
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(
"select * from customers",mySqlConnection);
DataSet myDataSet = new DataSet();
mySqlDataAdapter.Fill(myDataSet,"Customers");
mySqlDataAdapter.SelectCommand.CommandText =
"select * from orders";
mySqlDataAdapter.Fill(myDataSet,"Orders");
mySqlDataAdapter.SelectCommand.CommandText =
"select * from orders";
mySqlDataAdapter.Fill(myDataSet,"Orders");
Orders

Customers
DataSet:
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.

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");



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.
Note
Delivery Tip
Tell students that they can
create new relationships
between the tables in a
DataSet.
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
!
DataViews Can be Customized to Present a Subset of
Data from a DataTable
!
The DefaultView Property Returns the Default DataView
for the Table
!
Setting Up Different Views
myDataView.Sort = "Country";
myDataView.RowFilter = "Country = 'Argentina'";
myDataView.Sort = "Country";
myDataView.RowFilter = "Country = 'Argentina'";
DataView myDataView =
myDataSet.Tables["Customers"].DefaultView;
DataView myDataView =
myDataSet.Tables["Customers"].DefaultView;

*****************************

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;


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";

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.
Note
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
!
SQLCommandBuilder generates Update command
!
Set the MissingSchemaAction property
!
Add a row
!

To submit the data
mySqlDataAdapter.MissingSchemaAction =
MissingSchemaAction.AddWithKey;
mySqlDataAdapter.MissingSchemaAction =
MissingSchemaAction.AddWithKey;
SqlCommandBuilder mySqlCommandBuilder = new
SqlCommandBuilder(mySqlDataAdapter);
SqlCommandBuilder mySqlCommandBuilder = new
SqlCommandBuilder(mySqlDataAdapter);
DataRow myDataRow =
myDataSet.Tables["Customers"].NewRow();
myDataRow["CustomerId"] = "NewID";
// ...
myDataSet.Tables["Customers"].Rows.Add(myDataRow);
DataRow myDataRow =
myDataSet.Tables["Customers"].NewRow();
myDataRow["CustomerId"] = "NewID";
// ...
myDataSet.Tables["Customers"].Rows.Add(myDataRow);
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);

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.

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×