Вы находитесь на странице: 1из 10

ADO.

NET
Overview of ADO.NET
Among the many things that are changing with .NET is data access. Under the .NET Framework, data access is handled by a set of classes called ADO.NET which are essentially an augmentation of the existing ActiveX Data Objects (ADO). ADO.NET is entirely based on XML. There is no Recordset object. ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as well as data sources exposed through OLE DB and XML. Data-sharing consumer applications can use ADO.NET to connect to these data sources and retrieve, manipulate, and update data. ADO.NET cleanly factors data access from data manipulation into discrete components that can be used separately or in tandem. ADO.NET includes .NET Framework data providers for connecting to a database, executing commands, and retrieving results. Those results are either processed directly, or placed in an ADO.NET DataSet object in order to be exposed to the user in an ad-hoc manner, combined with data from multiple sources, or remoted between tiers. The ADO.NET DataSet object can also be used independently of a .NET Framework data provider to manage data local to the application or sourced from XML Under ADO.NET, the functionality of the Recordset has been split into three group. The DataReader object allows you to perform a single pass through a set of records as efficiently as possible. In ADO, this was achieved using a forwardonly, server-side cursor. The DataSet and The DataSetCommand objects allow you to create a client-side cache of one or more related Recordsets and process it in a disconnected fashion. In ADO, a client-side cursor was used for much the same thing. By separating out these two very different sets of functionality, ADO.NET can provide tailored support for each approach, as well as exposing more power. The third area of functionality is everything else that ADO can do. This includes, for example, using a connection-oriented approach to updating data through pessimistic locking. You cant do this in ADO.NET (at least not as it stands) which means you will certainly continue to use classic ADO for some time yet. ADO.NET is firmly targeted at n-tier web-friendly applications: it doesnt intend to tread on ADOs toes in all areas.

ADO.NET Architecture Data processing has traditionally relied primarily on a connection-based, two-tier model. As data processing increasingly uses multi-tier architectures, programmers are switching to a disconnected approach to provide better scalability for their applications.

XML and ADO.NET ADO.NET leverages the power of XML to provide disconnected access to data. ADO.NET was designed hand-in-hand with the XML classes in the .NET Framework both are components of a single architecture. ADO.NET and the XML classes in the .NET Framework converge in the DataSet object. The DataSet can be populated with data from an XML source, whether it is a file or an XML stream. The DataSet can be written as World Wide Web Consortium (W3C) compliant XML, including its schema as XML Schema definition language (XSD) schema, regardless of the source of the data in the DataSet. Because the native serialization format of the DataSet is XML, it is an excellent medium for moving data between tiers making the DataSet an optimal choice for remoting data and schema context to and from an XML Web service.

ADO.NET Components The ADO.NET components have been designed to factor data access from data manipulation. There are two central components of ADO.NET that accomplish this: the DataSet, and the .NET Framework data provider, which is a set of components including the Connection, Command, DataReader, and DataAdapter objects. The ADO.NET DataSet is the core component of the disconnected architecture of ADO.NET. The DataSet is explicitly designed for data access independent of any data source. As a result it can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. The DataSet contains a collection of one or more DataTable objects made up of rows and columns of data, as well as primary key, foreign key, constraint, and relation information about the data in the DataTable objects.

The other core element of the ADO.NET architecture is the .NET Framework data provider, whose components are explicitly designed for data manipulation and fast, forward-only, read-only access to data. The Connection object provides connectivity to a data source. The Command object enables access to database commands to return data, modify data, run stored procedures, and send or retrieve parameter information. The DataReader provides a high-performance stream of data from the data source. Finally, the DataAdapter provides the bridge between the DataSet object and the data source. The DataAdapter uses Command objects to execute SQL commands at the data source to both load the DataSet with data, and reconcile changes made to the data in the DataSet back to the data source. You can write .NET Framework data providers for any data source. The .NET Framework ships with two .NET Framework data providers: The .NET Framework Data Provider for SQL Server. The .NET Framework Data Provider for OLE DB. Remoting or Marshaling Data between Tiers and Clients The design of the DataSet enables you to easily transport data to clients over the Web using XML Web services, as well as allowing you to marshal data between .NET components using .NET Remoting services Design Goals for ADO.NET ADO.NET was designed to meet the needs of this new programming model: disconnected data architecture, tight integration with XML, common data representation with the ability to combine data from multiple and varied data sources, and optimized facilities for interacting with a database, all native to the .NET Framework. Leverage Current ADO Knowledge ADO.NET is an intrinsic part of the .NET Framework without seeming completely foreign to the ADO programmer. ADO.NET coexists with ADO. While most new .NET-based applications will be written using ADO.NET, ADO remains available to the .NET programmer through .NET COM interoperability services. Support the N-Tier Programming Model ADO.NET provides first-class support for the disconnected, n-tier programming environment for which many new applications are written. The concept of working with a disconnected set of data has become a focal point in the programming model. The ADO.NET solution for n-tier programming is the DataSet. Integrate XML Support XML and data access are intimately tied XML is all about encoding data, and data access is increasingly becoming all about XML. The .NET Framework does not just support Web standards it is built entirely on top of them.

XML support is built into ADO.NET at a very fundamental level. The XML classes in the .NET Framework and ADO.NET are part of the same architecture they integrate at many different levels. You no longer have to choose between the data access set of services and their XML counterparts; the ability to cross over from one to the other is inherent in the design of both. Comparison of ADO.NET and ADO In-memory Representations of Data In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the dataset. There are important differences between them. A 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. Each DataTable object typically corresponds to a single database table or view. In this way, a dataset can mimic the structure of the underlying database. Data Navigation and Cursors In ADO you scan sequentially through the rows of the recordset using the ADO MoveNext method. 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 via ordinal or primary key index.. A cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object. Minimized Open Connections In ADO.NET you open connections only long enough to perform a database operation, such as a Select or Update. You can read rows into a dataset and then work with them without staying connected to the data source. In ADO the recordset can provide disconnected access, but ADO is designed primarily for connected access. There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source. The important difference is that in ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database by optimizing for performance, performing data validation checks, or adding any other extra processing. Sharing Data Between Applications

Transmitting an ADO.NET dataset between applications is much easier than transmitting an ADO disconnected recordset. To transmit an ADO disconnected recordset from one component to another, you use COM marshalling. To transmit data in ADO.NET, you use a dataset, which can transmit an XML stream. The transmission of XML files offers the following advantages over COM marshalling: Richer data types COM marshalling provides a limited set of data types those defined by the COM standard. Because the transmission of datasets in ADO.NET is based on an XML format, there is no restriction on data types. Thus, the components sharing the dataset can use whatever rich set of data types they would ordinarily use. Performance Transmitting a large ADO recordset or a large ADO.NET dataset can consume network resources; as the amount of data grows, the stress placed on the network also rises. Both ADO and ADO.NET let you minimize which data is transmitted. But ADO.NET offers another performance advantage, in that ADO.NET does not require data-type conversions. ADO, which requires COM marshalling to transmit records sets among components, does require that ADO data types be converted to COM data types. Penetrating Firewalls A firewall can interfere with two components trying to transmit disconnected ADO recordsets. Remember, firewalls are typically configured to allow HTML text to pass, but to prevent system-level requests (such as COM marshalling) from passing. Because components exchange ADO.NET datasets using XML, firewalls can allow datasets to pass.

.NET Framework Data Providers


A .NET Framework data provider is used for connecting to a database, executing commands, and retrieving results. The .NET Framework data provider is designed to be lightweight, creating a minimal layer between the data source and your code, increasing performance without sacrificing functionality. Object Connection Command Description Establishes a connection to a specific data source. Executes a command against a data source. Exposes Parameters and can execute within the scope of a Transaction from a Connection. Reads a forward-only, read-only stream of data from a data source

DataReader

DataAdapter

Populates a DataSet and resolves updates with the data source.

Connection Connecting to SQL Server Using ADO.NET The .NET Framework Data Provider for SQL Server provides connectivity to Microsoft SQL Server version 7.0 or later using the SqlConnection object. The .NET Framework Data Provider for SQL Server supports a connection string format that is similar to the OLE DB (ADO) connection string format.

In ADO.NET you create and manage connections using connection objects:


SqlConnection - an object that manages a connection to a SQL Server version 7.0 or later. It is optimized for use with SQL Server 7.0 or later by (among other things) bypassing the OLE DB layer. OleDbConnection - an object that manages a connection to any data store accessible via OLE DB. OdbcConnection - an object that manages a connection to a data source created by using a connection string or ODBC data source name (DSN). OracleConnection - an object that manages a connection to Oracle databases.

Command In ADO there are three possible ways to update a data source. One is through direct SQL commands, like INSERT, DELETE and UPDATE, or more complex and sophisticated stored procedures. Another is through batch update, where you submit a new image of a certain table to the server all at once. The third way is through direct fields update using server cursors.

After establishing a connection to a data source, you can execute commands and return results from the data source using a Command object. You can create a command using the Command constructor, which takes optional arguments of an SQL statement to execute at the data source, a Connection object, and a Transaction object. You can also create a command for a particular Connection using the CreateCommand method of the Connection object. The SQL statement of the Command object can be queried and modified using the CommandText property.
ADO.NET Command Objects Using an adapter, you can read, add, update, and delete records in a data source. To allow you to specify how each of these operations should occur, an adapter supports the following four properties:

SelectCommand reference to a command (SQL statement or stored procedure name) that retrieves rows from the data store. InsertCommand reference to a command for inserting rows into the data store. UpdateCommand reference to a command for modifying rows in the data store. DeleteCommand reference to a command for deleting rows from the data store.

DataReader You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database. Results are returned as the query executes, and are stored in the network buffer on the client until you request them using the Read method of the DataReader. Using the DataReader can increase application performance both by retrieving data as soon as it is available, rather than waiting for the entire results of the query to be returned, and (by default) storing only one row at a time in memory, reducing system overhead. After creating an instance of the Command object, you create a DataReader by calling Command.ExecuteReader to retrieve rows from a data source, as shown in the following example: DataAdapter Data adapters are an integral part of ADO.NET managed providers, which are the set of objects used to communicate between a data source and a dataset. (In addition to adapters, managed providers include connection objects, data reader objects, and command objects.) Adapters are used to exchange data between a data source and a dataset. In many applications, this means reading data from a database into a dataset, and then writing changed data from the dataset back to the database. However, a data adapter can move data between any source and a dataset. For example, there could be an adapter that moves data between a Microsoft Exchange server and a dataset. Generally, adapters are configurable to allow you to specify what data to move into and out of the dataset. Often this takes the form of references to SQL statements or stored procedures that are invoked to read or write to a database. Visual Studio makes these data adapters available for use with databases: The OleDbDataAdapter object is suitable for use with any data source exposed by an OLE DB provider. The SqlDataAdapter object is specific to SQL Server. Because it does not have to go through an OLE DB layer, it is faster than the OleDbDataAdapter. However, it can only be used with SQL Server 7.0 or later. The OdbcDataAdapter object is optimized for accessing ODBC data sources. The OracleDataAdapter object is optimized for accessing Oracle databases.

Note Data Adapters, Data Connections, Data Commands, and Data Readers are the components that make up a .NET Framework data provider. Microsoft and third-party providers can make available other .NET data providers that can be integrated into Visual Studio. Populating a DataSet from a DataAdapter The ADO.NET DataSet is a memory-resident representation of data that provides a consistent relational programming model independent of the data source. The DataSet represents a complete set of data including tables, constraints, and relationships among the tables. Because the DataSet is independent of the data source, a DataSet can include data local to the application, as well as data from multiple data sources. Interaction with existing data sources is controlled through the DataAdapter. The SelectCommand property of the DataAdapter is a Command object that retrieves data from the data source. The InsertCommand, UpdateCommand, and DeleteCommand properties of the DataAdapter are Command objects that manage updates to the data in the data source according to modifications made to the data in the DataSet.. The Fill method of the DataAdapter is used to populate a DataSet with the results of the SelectCommand of the DataAdapter. Fill takes as its arguments a DataSet to be populated, and a DataTable object, or the name of the DataTable to be filled with the rows returned from the SelectCommand. The following code example creates an instance of a DataAdapter that uses a Connection to the Microsoft SQL Server Northwind database and populates a DataTable in a DataSet with the list of customers. The SQL statement and Connection arguments passed to the DataAdapter constructor are used to create the SelectCommand property of the DataAdapter. The .NET Framework Data Provider for SQL Server The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. It is lightweight and performs well because it is optimized to access a SQL Server directly without adding an OLE DB or Open Database Connectivity (ODBC) layer. The following illustration contrasts the .NET Framework Data Provider for SQL Server with the .NET Framework Data Provider for OLE DB. The .NET Framework Data Provider for OLE DB communicates to an OLE DB data source through both the OLE DB Service component, which provides connection pooling and transaction services, and the OLE DB Provider for the data source Note The .NET Framework Data Provider for ODBC has a similar architecture to the .NET Framework Data Provider for OLE DB; for example, it calls into an ODBC Service Component.

Comparison of the .NET Framework Data Provider for SQL Server and the .NET Framework Data Provider for OLE DB

To use the .NET Framework Data Provider for SQL Server, you must have access to Microsoft SQL Server 7.0 or later. .NET Framework Data Provider for SQL Server classes are located in the System.Data.SqlClient namespace. For earlier versions of Microsoft SQL Server, use the .NET Framework Data Provider for OLE DB with the SQL Server OLE DB Provider (SQLOLEDB). The .NET Framework Data Provider for SQL Server supports both local and distributed transactions. For distributed transactions, the .NET Framework Data Provider for SQL Server, by default, automatically enlists in a transaction and obtains transaction details from Windows 2000 Component Services. The .NET Framework Data Provider for SQL Server requires the installation of Microsoft Data Access Components (MDAC) version 2.6 or later. In ADO.NET, you control transactions using the Connection and Transaction objects. You can initiate a local transaction using Connection.BeginTransaction. Once you have begun a transaction, you can enlist a command in that transaction using the Transaction property of the Command object. You can then use the Transaction object to commit or rollback modifications made at the data source based on the success or failure of the components of the transaction. Performing a Transaction Using ADO.NET You can begin, commit and roll back a transaction using the Connection and Transaction objects. The following steps are used to perform a transaction. To perform a transaction Call the BeginTransaction method of the Connection object to mark the start of the transaction. The BeginTransaction method returns a reference to the Transaction. This reference is assigned to the Command objects that are enlisted in the transaction. Assign the Transaction object to the Transaction property of the Command to be executed. If a Command is executed on a Connection with

an active Transaction, and the Transaction object has not been assigned to the Transaction property of the Command, an exception is thrown. Execute the required commands. Call the Commit method of the Transaction object to complete the transaction, or call the Rollback method to cancel the transaction.

The DataSet, DataReader, DataSetCommand Object


Introduction to Datasets Datasets store data in a disconnected cache. The structure of a dataset is similar to that of a relational database; it exposes a hierarchical object model of tables, rows, and columns. In addition, it contains constraints and relationships defined for the dataset. Note You use datasets if you want to work with a set of tables and rows while disconnected from the data source. Using a dataset is not always an optimal solution for designing data access. You can create and manipulate datasets using the following portions of the .NET Framework namespaces. Dataset Namespace

The fundamental parts of a dataset are exposed to you through standard programming constructs such as properties and collections. For example: The DataSet class includes the Tables collection of data tables and the Relations collection of DataRelation objects. The DataTable class includes the Rows collection of table rows, the Columns collection of data columns, and the ChildRelations and ParentRelations collections of data relations. The DataRow class includes the RowState property, whose values indicate whether and how the row has been changed since the data table was first loaded from the database. Possible values for the RowState property include Deleted, Modified, New, and Unchanged.

Вам также может понравиться