Добавил:
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

3

 

 

 

The ADO.NET Object Model

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.

.ASPX Page

DataReader

Command

Company:Company:

Northwind Traders

Northwind Traders

Database

Connection

DataAdapter

DataView

DataView

DataSet

List-Bound

 

List-Bound

 

Control

 

Control

.ASPX Page

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

Delivery Tip

Point out that there are ADO and SQL Server versions of the Connection, Command, DataAdapter, and DataReader objects.

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.

4Module 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 Serverversion 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 databinding 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.

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

Multimedia: Using ADO.NET to Access Data

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.

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

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.

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.

 

 

 

 

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

7

Recordsets vs. DataSets

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Topic Objective

 

 

 

 

 

 

 

 

To highlight the differences

 

 

Feature

Recordset

DataSet

 

 

 

 

between DataSets and

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Recordsets.

 

 

 

 

 

 

 

 

 

Number of tables

One table

Multiple tables

 

 

 

 

Lead-in

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

In ADO, you used

 

 

 

 

 

 

 

 

 

Relationships

Based on join

Includes relationships

 

 

 

 

Recordsets.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Moving through data

Move row-by-row

Navigate via

 

 

 

 

 

 

 

 

 

relationships

 

 

 

 

 

 

 

Data connections

Connected or

Disconnected

 

 

 

 

 

 

 

 

disconnected

 

 

 

 

 

 

 

 

Transmitting data

COM marshalling

Transmit XML file

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

*****************************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.

8Module 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

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.

!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

10

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

Connecting to a Data Source

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.

! Using SqlConnection

SqlConnection mySqlConnection = new SqlConnection mySqlConnection = new SqlConnection("server=(local)\\NetSDK;!

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

! Using OleDbConnection

OleDbConnection myOleDbConnection = new OleDbConnection myOleDbConnection = new OleDbConnection("server=(local)\\NetSDK; !

OleDbConnection("server=(local)\\NetSDK; ! Trusted_Connection=yes;database=northwind; ! Trusted_Connection=yes;database=northwind; ! provider=sqloledb");

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.

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.

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

Warning 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.

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

11

 

 

 

Delivery Tip

Stress to students that all examples in the module and lab will use SqlConnection objects.

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

Recommended for middle-tier applications that use Microsoft

.NET Data Provider

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

Recommended for middle-tier applications that use Microsoft

Data Provider

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.

12

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

" Accessing Data with DataSets

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.

!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.

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