Sei sulla pagina 1di 17

ADO .

NET

Most applications need data access at one point of time making it a crucial component when
working with applications. Data access is making the application interact with a database, where
all the data is stored. Different applications have different requirements for database access. VB
.NET uses ADO .NET (Active X Data Object) as it's data access and manipulation protocol
which also enables us to work with data on the Internet. Let's take a look why ADO .NET came
into picture replacing ADO.

Evolution of ADO.NET

The first data access model, DAO (data access model) was created for local databases with the
built-in Jet engine which had performance and functionality issues. Next came RDO (Remote
Data Object) and ADO (Active Data Object) which were designed for Client Server architectures
but, soon ADO took over RDO. ADO was a good architecture but as the language changes so is
the technology. With ADO, all the data is contained in a recordset object which had problems
when implemented on the network and penetrating firewalls. ADO was a connected data access,
which means that when a connection to the database is established the connection remains open
until the application is closed. Leaving the connection open for the lifetime of the
application raises concerns about database security and network traffic. Also, as databases are
becoming increasingly important and as they are serving more people, a connected data access
model makes us think about its productivity. For example, an application with connected data
access may do well when connected to two clients, the same may do poorly when connected to
10 and might be unusable when connected to 100 or more. Also, open database connections use
system resources to a maximum extent making the system performance less effective.

Why ADO.NET?

To cope up with some of the problems mentioned above, ADO .NET came into existence. ADO
.NET addresses the above mentioned problems by maintaining a disconnected database access
model which means, when an application interacts with the database, the connection is opened to
serve the request of the application and is closed as soon as the request is completed. Likewise, if
a database is Updated, the connection is opened long enough to complete the Update operation
and is closed. By keeping connections open for only a minimum period of time, ADO .NET
conserves system resources and provides maximum security for databases and also has less
impact on system performance. Also, ADO .NET when interacting with the database uses
XML and converts all the data into XML format for database related operations making them
more efficient.

The ADO.NET Data Architecture

Data Access in ADO.NET relies on two components: DataSet and Data Provider.

DataSet
The dataset is a disconnected, in-memory representation of data. It can be considered as a local
copy of the relevant portions of the database. The DataSet is persisted in memory and the data in
it can be manipulated and updated independent of the database. When the use of this DataSet is
finished, changes can be made back to the central database for updating. The data in DataSet can
be loaded from any valid data source like Microsoft SQL server database, an Oracle database or
from a Microsoft Access database.

Data Provider

The Data Provider is responsible for providing and maintaining the connection to the database. A
DataProvider is a set of related components that work together to provide data in an efficient and
performance driven manner. The .NET Framework currently comes with two DataProviders: the
SQL Data Provider which is designed only to work with Microsoft's SQL Server 7.0 or later and
the OleDb DataProvider which allows us to connect to other types of databases like Access and
Oracle. Each DataProvider consists of the following component classes:

The Connection object which provides a connection to the database


The Command object which is used to execute a command
The DataReader object which provides a forward-only, read only, connected recordset
The DataAdapter object which populates a disconnected DataSet with data and performs update

Data access with ADO.NET can be summarized as follows:

A connection object establishes the connection for the application with the database. The
command object provides direct execution of the command to the database. If the command
returns more than a single value, the command object returns a DataReader to provide the data.
Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be
updated using the command object or the DataAdapter.
Component classes that make up the Data Providers

The Connection Object

The Connection object creates the connection to the database. Microsoft Visual Studio .NET
provides two types of Connection classes: the SqlConnection object, which is designed
specifically to connect to Microsoft SQL Server 7.0 or later, and the OleDbConnection object,
which can provide connections to a wide range of database types like Microsoft Access and
Oracle. The Connection object contains all of the information required to open a connection to
the database.

The Command Object


The Command object is represented by two corresponding classes: SqlCommand and
OleDbCommand. Command objects are used to execute commands to a database across a data
connection. The Command objects can be used to execute stored procedures on the database, SQL
commands, or return complete tables directly. Command objects provide three methods that are
used to execute commands on the database:

ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE
or DELETE
ExecuteScalar: Returns a single value from a database query
ExecuteReader: Returns a result set by way of a DataReader object

The DataReader Object

The DataReader object provides a forward-only, read-only, connected stream recordset from a
database. Unlike other components of the Data Provider, DataReader objects cannot be directly
instantiated. Rather, the DataReader is returned as the result of the Command object's
ExecuteReader method. The SqlCommand.ExecuteReader method returns a SqlDataReader
object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object.
The DataReader can provide rows of data directly to application logic when you do not need to
keep the data cached in memory. Because only one row is in memory at a time, the DataReader
provides the lowest overhead in terms of system performance but requires the exclusive use of an
open Connection object for the lifetime of the DataReader.

The DataAdapter Object

The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is
essentially the middleman facilitating all communication between the database and a DataSet.
The DataAdapter is used either to fill a DataTable or DataSet with data from the database with
it's Fill method. After the memory-resident data has been manipulated, the DataAdapter can
commit the changes to the database by calling the Update method. The DataAdapter provides
four properties that represent database commands:

SelectCommand
InsertCommand
DeleteCommand
UpdateCommand

When the Update method is called, changes in the DataSet are copied back to the database and
the appropriate InsertCommand, DeleteCommand, or UpdateCommand is executed.

NET Framework Developer's Guide


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.

The DataSet can also be synchronized with an XmlDataDocument to provide relational and
hierarchical access to data in real time. For more information, see Synchronizing a DataSet with
an XmlDataDocument.

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
and the .NET Framework Data Provider for OLE DB.

The following diagram illustrates the components of ADO.NET architecture.

ADO.NET architecture

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. You can also remote a strongly typed DataSet in this fashion. For an
overview of XML Web services, see XML Web Services Overview. For an example of
consuming a DataSet from an XML Web service, see Consuming a DataSet from an XML Web
Service.

An overview of remoting services can be found in the .NET Remoting Overview. Note that
DataTable objects can also be used with remoting services, but cannot be transported via an
XML Web service.

ADO.NET Platform Requirements


The Microsoft .NET Framework SDK (including ADO.NET) is supported on Microsoft®
Windows® 2000, Microsoft® Windows NT® 4 with Service Pack 6a, Microsoft® Windows®
Millennium Edition, Microsoft® Windows® 98, and Microsoft® Windows® SE. Use of the
.NET Framework Data Provider for SQL Server or .NET Framework Data Provider for OLE DB
requires the installation of Microsoft Data Access Components version 2.6 or later.
The following code example shows how to include the System.Data namespace in your
applications, in order to use ADO.NET.

[Visual Basic]
Imports System.Data
[C#]
using System.Data;

The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes
found in System.Xml.dll. When compiling code that uses the System.Data namespace, reference
both System.Data.dll and System.Xml.dll. For an example of compiling an ADO.NET
application using a command line compiler, see ADO.NET Sample Application.

Choosing a DataReader or a DataSet


When deciding whether your application should use a DataReader (see Retrieving Data Using
the DataReader) or a DataSet (see Creating and Using DataSets), you should consider the type
of functionality that your application requires. Use a DataSet to do the following:

 Remote data between tiers or from an XML Web service.


 Interact with data dynamically such as binding to a Windows Forms control or combining
and relating data from multiple sources.
 Cache data locally in your application.
 Provide a hierarchical XML view of relational data and use tools like an XSL
Transformation or an XML Path Language (XPath) Query on your data. For more
information, see XML and the DataSet.
 Perform extensive processing on data without requiring an open connection to the data
source, which frees the connection to be used by other clients.

If you do not require the functionality provided by the DataSet, you can improve the
performance of your application by using the DataReader to return your data in a forward-only
read-only fashion. Although the DataAdapter uses the DataReader to fill the contents of a
DataSet (see Populating a DataSet from a DataAdapter), by using the DataReader you can
receive performance gains because you will save memory that would be consumed by the
DataSet, as well as saving the processing required to create and fill the contents of th

ADO.NET is a set of computer software components that can be used by programmers to access
data and data services. It is a part of the base class library that is included with the Microsoft
.NET Framework. It is commonly used by programmers to access and modify data stored in
relational database systems, though it can also be used to access data in non-relational sources.
ADO.NET is sometimes considered an evolution of ActiveX Data Objects (ADO) technology,
but was changed so extensively that it can be considered an entirely new product.
This technology is a part of .NET Framework 3.0 (having been part of the framework since
version 1.0)
Contents
[hide]

 1 Architecture
o 1.1 Data provider
o 1.2 DataSets
 2 ADO.NET and Visual Studio
 3 Entity Framework
 4 Third-party data providers
 5 See also
 6 External links

[edit] Architecture
ADO.NET consists of two primary parts:

[edit] Data provider

These classes provide access to a data source, such as a Microsoft SQL Server or Oracle
database and OLEDB data provider. Each data source has its own set of provider objects, but
they each have a common set of utility classes:

 Connection: Provides a connection used to communicate with the data source. Also acts
as an abstract factory for command objects.
 Command: Used to perform some action on the data source, such as reading, updating, or
deleting relational data.
 Parameter: Describes a single parameter to a command. A common example is a
parameter to a stored procedure.
 DataAdapter: A bridge used to transfer data between a Data source and a DataSet object
(see below).
 DataReader: Used to efficiently process a large list of results one record at a time. It
allows records to be accessed in a read-only, forward-only mode, i.e., records have to be
accessed in sequential order; they can neither be randomly accessed nor can a record
which has been processed previously be accessed again.

[edit] DataSets

DataSet is objects, a group of classes describing a simple in-memory relational database, were
the star of the show in the initial release (1.0) of the Microsoft .NET Framework. The classes
form a containment hierarchy:

 A DataSet object represents a schema (either an entire database or a subset of one). It can
contain tables and relationships between those tables.
o A DataTable object represents a single table in the database. It has a name, rows,
and columns.
 A DataView object overlays a DataTable and sorts the data (much like an
SQL "order by" clause) and filters the records (much like an SQL "where"
clause) if a filter is set. An in-memory index is used to facilitate these
operations. All DataTables have a default filter, while any number of
additional DataViews can be defined, reducing interaction with the
underlying database and thus improving performance.
 A DataColumn represents a column of the table, including its
name and type.
 A DataRow object represents a single row in the table; it allows
reading and updating of values in that row, likewise retrieving any
rows that are related to it through a primary-key foreign-key
relationship.
 A DataRowView represents a single row of a DataView. The
distinction between a DataRow and DataRowView is important
when iterating over a result set.
o A DataRelation is a relationship between tables, e.g. a primary-key foreign-key
relationship. This is useful for enabling DataRow's functionality of retrieving
related rows.
o A Constraint describes an enforced property of the database, e.g. the uniqueness
of the values in a primary key column. When data is being modified any
violations that arise shall cause exceptions.

A DataSet is populated from a database by a DataAdapter whose Connection and Command


properties have been set. However, a DataSet can save its contents to XML (optionally with an
XSD schema), or populate itself from XML, making it exceptionally useful for web services,
distributed computing, and occasionally-connected applications.

[edit] ADO.NET and Visual Studio


Functionality exists in the Visual Studio IDE to create specialized subclasses of the DataSet
classes for a particular database schema, allowing convenient access to each field through
strongly-typed properties. This helps catch more programming errors at compile-time, making
the IDE's Intellisense feature more beneficial.

[edit] Entity Framework


Main article: ADO.NET Entity Framework

ADO.NET Entity Framework is a set of data access APIs for the Microsoft .NET Framework,
similar to the Java Persistence API, targeting the version of ADO.NET that ships with .NET
Framework 3.5. ADO.NET Entity Framework is included with .NET Framework 3.5 Service
Pack 1 and Visual Studio 2008 Service Pack 1, released on 11 Aug 2008. An Entity Framework
Entity is an object which has a key representing the primary key of a logical datastore entity. A
conceptual Entity Data Model (Entity-relationship model) is mapped to a datastore schema
model. Using the Entity Data Model, the Entity Framework allows data to be treated as entities
independently of their underlying datastore representations.

Entity SQL is a SQL-like language for querying the Entity Data Model (instead of the underlying
datastore). Similarly, Linq extension Linq-to-Entities provides typed querying on the Entity Data
Model. Entity SQL and Linq-to-Entities queries are converted internally into a Canonical Query
Tree which is then converted into a query understandable to the underlying datastore (e.g. into
SQL in the case of a Relational database). The entities can be using their relationships, and their
changes committed back to the datastore.

[edit] Third-party data providers


There is a wide range of data providers that are used to gain access to the database engines like
Oracle, SQL Server, MySQL, PostgreSQL, SQLite, DB2, and others:

 Connector/Net: native data provider for MySQL database server (free)


 DataDirect Connect for ADO.NET: data providers for Oracle, DB2, SQL Server, and
Sybase database servers from DataDirect (commercial)
 DB2 .NET: data provider for DB2 database server from IBM (free)
 dotConnect: data providers for Oracle, MySQL, PostgreSQL, SQL Server, and SQLite
database servers from Devart (free and commercial)
 Npgsql: open source data povider for PostgreSQL database server (free)
 Oracle Data Provider for .NET (ODP.NET): data provider for Oracle database server
from Oracle (free)
 VistaDB: 100% managed ADO.NET provider with SQL Server like syntax
 RDM Server: data povider for the RDM Server database system from Birdstep
Technology, Inc (free)

Lesson 01: Introduction to ADO.NET

This lesson is an introduction to ADO.NET. It introduces primary ADO.NET concepts and


objects that you will learn about in later lessons. Here are the objectives of this lesson:

 Learn what ADO.NET is.


 Understand what a data provider is.
 Understand what a connection object is.
 Understand what a command object is.
 Understand what a DataReader object is.
 Understand what a DataSet object is.
 Understand what a DataAdapter object is.

Introduction

ADO.NET is an object-oriented set of libraries that allows you to interact with data sources.
Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or
an XML file. For the purposes of this tutorial, we will look at ADO.NET as a way to interact
with a data base.

As you are probably aware, there are many different types of databases available. For example,
there is Microsoft SQL Server, Microsoft Access, Oracle, Borland Interbase, and IBM DB2, just
to name a few. To further refine the scope of this tutorial, all of the examples will use SQL
Server.

You can download the Microsoft SQL Server 2000 Desktop Engine (MSDE 2000) here:

http://www.microsoft.com/sql/msde/downloads/download.asp

MSDE contains documentation on how to perform an installation. However, for your


convenience, here are quick instructions on how to install MSDE:

http://www.asp.net/msde/default.aspx?tabindex=0&tabid=1

MSDE 2000 is a scaled down version of SQL Server. Therefore, everything you learn in this
tutorial and all code will work with SQL Server. The examples will use the Northwind
database. This is a tutorial is specifically for ADO.NET. MSDE is not part of ADO.NET, but it
is one of the many data sources you can interact with by using ADO.NET If you need help with
MSDE 2000, I refer you to the Microsoft Web site, where you can find pertinent information on
licensing and technical assistance:

http://www.microsoft.com/sql/msde/
Data Providers

We know that ADO.NET allows us to interact with different types of data sources and different
types of databases. However, there isn't a single set of classes that allow you to accomplish this
universally. Since different data sources expose different protocols, we need a way to
communicate with the right data source using the right protocol. Some older data sources use the
ODBC protocol, many newer data sources use the OleDb protocol, and there are more data
sources every day that allow you to communicate with them directly through .NET ADO.NET
class libraries.

ADO.NET provides a relatively common way to interact with data sources, but comes in
different sets of libraries for each way you can talk to a data source. These libraries are called
Data Providers and are usually named for the protocol or data source type they allow you to
interact with. table 1 lists some well known data providers, the API prefix they use, and the type
of data source they allow you to interact with.

table 1. ADO.NET Data Providers are class libraries that allow a common way to interact with specific data
sources or protocols. The library APIs have prefixes that indicate which provider they support.
Provider Name API prefix Data Source Description

ODBC Data
Odbc Data Sources with an ODBC interface. Normally older data bases.
Provider

OleDb Data
OleDb Data Sources that expose an OleDb interface, i.e. Access or Excel.
Provider

Oracle Data
Oracle For Oracle Databases.
Provider

SQL Data Provider Sql For interacting with Microsoft SQL Server.

Borland Data Generic access to many databases such as Interbase, SQL Server, IBM DB2,
Bdp
Provider and Oracle.

An example may help you to understand the meaning of the API prefix. One of the
first ADO.NET objects you'll learn about is the connection object, which allows you to
establish a connection to a data source. If we were using the OleDb Data Provider to
connect to a data source that exposes an OleDb interface, we would use a connection
object named OleDbConnection. Similarly, the connection object name would be
prefixed with Odbc or Sql for an OdbcConnection object on an Odbc data source or a
SqlConnection object on a SQL Server database, respectively. Since we are using
MSDE in this tutorial (a scaled down version of SQL Server) all the API objects will
have the Sql prefix. i.e. SqlConnection.
ADO.NET Objects

ADO.NET includes many objects you can use to work with data. This section
introduces some of the primary objects you will use. Over the course of this tutorial,
you'll be exposed to many more ADO.NET objects from the perspective of how they
are used in a particular lesson. The objects below are the ones you must know.
Learning about them will give you an idea of the types of things you can do with data
when using ADO.NET.

The SqlConnection Object

To interact with a database, you must have a connection to it. The connection helps
identify the database server, the database name, user name, password, and other
parameters that are required for connecting to the data base. A connection object is
used by command objects so they will know which database to execute the command
on.

The SqlCommand Object

The process of interacting with a database means that you must specify the actions
you want to occur. This is done with a command object. You use a command object
to send SQL statements to the database. A command object uses a connection object
to figure out which database to communicate with. You can use a command object
alone, to execute a command directly, or assign a reference to a command object to
an SqlDataAdapter, which holds a set of commands that work on a group of data as
described below.

The SqlDataReader Object

Many data operations require that you only get a stream of data for reading. The
data reader object allows you to obtain the results of a SELECT statement from a
command object. For performance reasons, the data returned from a data reader is a
fast forward-only stream of data. This means that you can only pull the data from the
stream in a sequential manner. This is good for speed, but if you need to manipulate
data, then a DataSet is a better object to work with.

The DataSet Object

DataSet objects are in-memory representations of data. They contain multiple


Datatable objects, which contain columns and rows, just like normal database tables.
You can even define relations between tables to create parent-child relationships.
The DataSet is specifically designed to help manage data in memory and to support
disconnected operations on data, when such a scenario make sense. The DataSet is
an object that is used by all of the Data Providers, which is why it does not have a
Data Provider specific prefix.
The SqlDataAdapter Object

Sometimes the data you work with is primarily read-only and you rarely need to make
changes to the underlying data source. Some situations also call for caching data in
memory to minimize the number of database calls for data that does not change. The
data adapter makes it easy for you to accomplish these things by helping to manage
data in a disconnected mode. The data adapter fills a DataSet object when reading
the data and writes in a single batch when persisting changes back to the database. A
data adapter contains a reference to the connection object and opens and closes the
connection automatically when reading from or writing to the database. Additionally,
the data adapter contains command object references for SELECT, INSERT, UPDATE,
and DELETE operations on the data. You will have a data adapter defined for each
table in a DataSet and it will take care of all communication with the database for
you. All you need to do is tell the data adapter when to load from or write to the
database.

Summary

ADO.NET is the .NET technology for interacting with data sources. You have several
Data Providers, which allow communication with different data sources, depending on
the protocols they use or what the database is. Regardless, of which Data Provider
used, you'll use a similar set of objects to interact with a data source. The
SqlConnection object lets you manage a connection to a data source. SqlCommand
objects allow you to talk to a data source and send commands to it. To have fast
forward-only read access to data, use the SqlDataReader. If you want to work with
disconnected data, use a DataSet and implement reading and writing to/from the
data source with a SqlDataAdapter.

This is just the beginning - the first of several lessons in the ADO.NET Tutorial. The
next one in this series is Lesson 02: The SqlConnection Object.

Your feedback and constructive contributions are welcome. Please feel free to
contact me for feedback or comments you may have about this lesson.

ADO.NET is a data access technology from Microsoft .Net Framework , which


provides communication between relational and non-relational systems through a
common set of components . ADO.NET consist of a set of Objects that expose data
access services to the .NET environment. ADO.NET is built for disconnected
architecture , so it enables truly disconnected Data Access and Data Manipulation
through its Dataset Object, which is completely independent from the Data Source.
The two key components of ADO.NET are Data Providers and DataSet . The .Net
Framework includes mainly three Data Providers for ADO.NET. They are the
Microsoft SQL Server Data Provider, OLEDB Data Provider and ODBC Data
Provider. SQL Server uses the SqlConnection object , OLEDB uses the
OleDbConnection Object and ODBC uses OdbcConnection Object respectively.

The four Objects from the .Net Framework provide the functionality of Data
Providers in the ADO.NET. They are Connection Object, Command Object ,
DataReader Object and DataAdapter Object. The Connection Object provides
physical connection to the Data Source. The Command Object uses to perform SQL
statement or stored procedure to be executed at the Data Source. The DataReader
Object is a stream-based , forward-only, read-only retrieval of query results from the
Data Source, which do not update the data. Finally the DataAdapter Object , which
populate a Dataset Object with results from a Data Source .

DataSet provides a disconnected representation of result sets from the Data Source,
and it is completely independent from the Data Source. DataSet provides much
greater flexibility when dealing with related Result Sets. DataSet consists of a
collection of DataTable objects that you can relate to each other with DataRelation
objects. The DataTable contains a collection of DataRow and DataCoulumn Object
which contains Data. The DataAdapter Object provides a bridge between the DataSet
and the Data Source.

In the following section you can see each of the ADO.NET components in details
with vb.net source code.

Potrebbero piacerti anche