Contents Overview 1 Connecting to a Data Source 10 Accessing Data with DataSets 12 Lab 16: Using ADO.NET to Access Data 34 Accessing Data with DataReaders 42 Review 56 Module 16 Op
Trang 1Contents
Overview 1
Connecting to a Data Source 10
Accessing Data with DataSets 12
Lab 16: Using ADO.NET to Access Data 34
Accessing Data with DataReaders 42
Review 56
Module 16 (Optional): Using Microsoft
ADO.NET to Access Data
Trang 2Information 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
Trang 3Instructor 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
Trang 4Multimedia 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
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
Trang 5Module 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
Trang 6! 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
Trang 7Overview
! 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
In this module, you will learn
about the data binding
features in ASP.NET
Trang 8" 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
Trang 9The ADO.NET Object Model
DataAdapter
Connection Database
Command
.ASPX Page
List-Bound Control
List-Bound Control
***************************** 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
Trang 10DataReader 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
Trang 11DataAdapter 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
Trang 12Multimedia: 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
Trang 13Recordsets vs DataSets
Transmit XML fileCOM marshalling
Transmitting data
DisconnectedConnected or
disconnectedData connections
Navigate via relationshipsMove row-by-row
Moving through data
Includes relationshipsBased on join
Relationships
Multiple tablesOne table
Number of tables
DataSet Recordset
Feature
***************************** 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
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
Trang 14Relationships
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
Trang 15***************************** 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 VisualC#™, 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
Trang 16Connecting to a Data Source
OleDbConnection myOleDbConnection = newOleDbConnection("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
Trang 17Using 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 http://msdn.microsoft.com/downloads
Delivery Tip
Stress to students that all
examples in the module and
lab will use SqlConnection
objects
Trang 18" 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
Trang 19Using 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
Trang 20The 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 based methods Aside from the improved readability of the code, a typed
collection-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
Trang 21Storing 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();
***************************** 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(
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
Trang 22The 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 =
//fill DataSet with first set of data DataSet myDataSet = new DataSet();
Trang 23DataView 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";
Trang 24Setting 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
Trang 25Updating a Database From a DataSet
! SQLCommandBuilder generates Update command
! Set the MissingSchemaAction property
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");
***************************** 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);
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
Trang 26Because 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;
myDataRow["CustomerId"] = "NewID";
myDataRow["ContactName"] = "New Name";
myDataRow["CompanyName"] = "New Company Name";
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
Trang 27Demonstration: Accessing Data with DataSets
***************************** 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
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
Tip
Trang 28Running 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
Trang 29Displaying Data in the DataGrid Control
! Create a Windows Forms DataGrid control
! Bind to a DataSet
! Using a custom view
dataGrid1 = new System.Windows.Forms.DataGrid();
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
Displaying data from a data source is extremely simple and flexible in either Windows Forms or ASP.NET These application development environments include a set of controls that perform the function of displaying data You only need to bind these controls to a data source
To display data on the client, you can use any list-bound control, such as the
DataGrid
Using the DataGrid Control
The DataGrid control is designed to produce output that resembles a worksheet In Visual Studio NET, you can drag and drop a DataGrid from the Toolbox onto the Design window This generates code to create a DataGrid
object as follows:
dataGrid1 = new System.Windows.Forms.DataGrid();
To bind a DataSet to a DataGrid control, you first set the DataSource property of the DataGrid to a DataTable, or DataVieweither the
DefaultView property of a DataSet or a custom DataView object
To specify a DataTable, set the DataMember property of the DataGrid to the name of the DataTable
Topic Objective
To describe how to display
data on the client DataGrid
controls
Lead-in
After you connect to a data
source and retrieve data
from it, the next step is to
display the data on the
client
Trang 30Example Binding to a DataSet
example, the following code will display only those customers in Argentina
Example Using a Custom View
DataView myDataView = myDataSet.Tables["Customers"].DefaultView;
myDataView.RowFilter = "Country = 'Argentina'";
dataGrid2.DataSource = myDataView;
Trang 31Demonstration: Displaying Data in a DataGrid
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
In this demonstration, you will see how to read data from a database into a
DataSet and then display it in a DataGrid control
Run the Visual Studio NET DataGrid project from the following location:
<install folder>\Democode\Mod16\Demo16.2
Running this program displays a button labeled “Load Data” and two DataGrid
controls Clicking the button reads region and customer data from a database
and displays them in the grids A DataView object is used to display only those
customers in Argentina
Topic Objective
To introduce the Data Grid
Lead-in
In this demonstration, you
will see how to create a
Windows Form that reads
data from a database and
displays it in a DataGrid
control
Trang 32" Using Stored Procedures
! Calling Stored Procedures
! Passing Parameters
! Calling Action Stored Procedures
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
In the past, data processing has been primarily connection-based Now, in an effort to make multi-tiered applications more efficient, data processing is turning to a message-based approach that revolves around chunks of
information In ADO.NET, this is accomplished by the DataAdapter object, which provides a bridge to retrieve and save data between a DataSet object and its source data store The DataAdapter object accomplishes this by invoking
the appropriate SQL commands against the data store
Both the SqlDataAdapter and the OleDbDataAdapter classes feature four command objects, InsertCommand, UpdateCommand, DeleteCommand, and SelectCommand These objects provide the create, update, delete, and read functions for a specific DataTable in the DataSet
These command objects are used when you want to perform a number of updates at the same time Instead of having one stored procedure to do it all,
you can put SQL Statements in each object and call the Update method
For more information about these command objects, see the NET Framework SDK documentation
However, the easier and more commonly used method of updating data in a database is to use stored procedures You can use stored procedures to read and modify data from a database You can call stored procedures both from
DataAdapter and Command objects
In this section, you will learn how to call stored procedures, pass parameterized stored procedures, and call action stored procedures
Topic Objective
To introduce the topics in
this section
Lead-in
When working with data
from a data source, the
ability to use stored
procedures is important