We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
Ve ok
Unit-VI
Data Access with ADO.NET ,
Assistant Professor: Bhise 6.6
ADO.NET, first introduced in version 1.0 of the NET Framework, provided an
extensive array of features to handle live data ina.connected mode or data that
is disconnected from its underlying data store. ADO.NET 1.0 was primarily
developed to address two specific problems in getting at data, The first had to do
with the user's need to access data once and to iterate through a collection of
data ina single instance. This need often arose in Web application development.
ADO.NET addresses a couple of the most common data-access strategies that are
used for applications today. When classic ADO was developed, many applications
could be connected to the data store almost indefinitely. Today, with the
explosion of the Internet as the means of data communication, a new data
technology is required to make data accessible and updateable in a disconnected
architecture ,
The first of these common data-access sceharios is one in which a user must
locate a collection of data and iférate through this data a single time. This is a
popular scenario for Web pages, When a request for data from a Web page that
you have created is received, you can simply fill a table with data from a data
_ Store. In this case, you go to the data store, grab the data that you want, send
the data across the wire, and then populate the table, In this scenario, the goal is
to get the data in place as fast as possible.
The second way to work with data in this disconnected architecture is to graba
collection of data and use this data separately from the data store itself. This
could be on the server or even on the client. Although the data is disconnected,
you want the ability to keep the data (with all of its tables and relations in place)
on the client side, Classic ADO data was represented by a single table that you
could iterate through. ADO.NET, however, can be a reflection of the data store
itself, with tables, columns, rows, and relations all in place. When you are donewith the client-side copy of the data, you can pet
in the local copy of data directly back into the data store:
-tiered environment (client-server),
easy to work with
sist the changes that you made ¥
Although classic ADO was geared for a two
ADO.NET addresses o multi-tiered environment. ADO.NET is
because it has a unified programming model, This unified programmins spece
makes working with data on the secver the same as working with dava on ine
client. Because the models are the same, you find yourself more productive when
working with ADO.NET.
ADO.NET provides a bridge between the front ‘end controls and the back end
database. The ADO.NET objects encapsulate all the data access operations and
the controls interact with these objects to display data, thus hiding the details of
movement of data.
The following figure shows the ADO.NET|ebjects ata glance:
[aaa
emma
ADO.NET is a set of classes that expose data access services for NET
Framework programmers. ADO.NET provides arich set of components for
creating distributed, data-sharing applications. I+ is an integral part of the NET
Framework, providing access to relational, XML, and application data. ADO.NET
supports a variety of development needs, including the creation of front-enddatabase clients and middle-tier business objects used by applications, tools,
languages, or Internet browsers,
Overview of ADO.NET Objects
Here'sa list of the most common ADO.NET objects:
+ Data connection objects—To start working with a database, you must have a
data connection. A data adapter needs a connection to a data source to read
and write data, and it uses OleDbConnection or SqlConnection objects to
communicate with a data source.
Data adapters—Data adapters are a very important part of ADO.NET. You use
‘them to communicate between a data source and a dataset. You ‘typically
configure a data adapter with SQL to executé ‘against the data source. The
two types of data adapters
are OleDbDataAdapter and SqlDataAdapter objects.
Command objects—Data adapters can read, add, update, and delete records in
@ data source. Toallow you to specify How each of these operations work, a
data adapter contains command objects'for each of them. Data adapters
support four oe Giveyou access to these command
objects: Select \InsertCommand, UpdateCommand,
and DeleteCommand.
a ?
Datasets—Datasets store data in a disconnected cache. The structure of a
dataset is similar to that of a relational database; it gives you access to an
object model of tables, rows, and columns, and it contains constraints and
relationships defined for the dataset. Datasets are supported
with DataSet objects.
+ DataTable objects—DataTable objects hold a data table froma data source.
Data tables contain two important properties: Columns, which is a collection of
the DataColumn objects that represent the columns of data ina table,
and Rows, which is a collection of DataRow objects, representing the rows of
data ina table.VW
* Data readers— DataReader objects hold a read-only, forward-only (ie ay
Can only move from one record to the succeeding record, not backwards) «,, e
data from a database. Using a data reader can increase Speed because oniy
row of data is in memory at a time.
* Data views—Data views represent a customized view of a single table that car
be filtered, searched, or sorted. In other words, a data view, supported by
the DataView class, is a data "snapshot" that takes up few resources,
+ Constraint objects—Datasets support constraints to check data integrity. A
constraint, supported by the Constraint class, isa rule that can be used when
rows are inserted, updated, or deleted to check the affected table after the
oPeration. There are two types of constraints: unique constraints check that
the new values j
one
Qnother table is updated, 1 a”
+ DataRelation objects—DataRelation objects Specify a relationship between
Parent and child tables, based on a key thaboth fables share,
* DataRow objects—DataRow objects correspond to a particular row in a data
table. You use the Item Property to get or set a value in a Particular field in
the row. X
DataColumn objects—DataColuiny objects correspond to the columns ina
table. Each object has’@'bat raT ype Property that specifies the kind of data
each column contains, such d,integers or string values,
Working with Connection Object
Using the Connection Object
The Connection object creates a link (ar connection) to a Specified data source.
This object must contain the necessary information to discover the specified data
source and to log in to it Properly using a defined username and password
combination. This information is provided via a single string called a connection
string. You can also store this connection String in the web.config file of your
applicationEvery type of data provider has a connection object of some kind. The data
provider for working with a SQL data store includes a SqlConnection class that
performs this type of operation. The SqiConnection object is a class that is
specific to the SqlClient provider, As discussed earlier in this chapter, the
SqiClient provider is built for working with the SQL Server 7.0 and higher
databases, The properties for the SqlConnection class are shown in the following
table.
Property Description
oaentleaitigg ‘Thi property hw yt rl er reid ft cmon ing tht atl
bbe tied by the aiconcection object
This read-only property returns the rane ofthe database to use after the
sonnection i opens
‘This read-only property miturns the name ofthe instanceof the SQL Server
‘database used by the 241 Connect Lencbjec.
“This read-only property returns the current state ofthe connection. The possible
Values are araten, loved, Conmect ing, Kamouting, Fetching. and Open.
atabase
Connecting to a data source is probably: the most common task when you are
working with data. This exampleand ithe‘ones that follow assume that you have a
SQL Server database. In order, o'cofinéct to your SQL Server database, you use
the SqiConneetion class
Listing 8-5: Connecting to a 5¢
VB Dim conn as SqiConnection conn = New SqlConnection("Data
Source=.\SQLEXPRESS;AttachDbFilename=
|DataDirectory| \NORTHWND.MDF:Integrated Security=True; User
Instance=True") ‘Put this string on one line in your code conn.Open()
To make this connection work, be sure that the proper namespaces are imported
before you start using any of the classes that work with SQL. The first step in
making a connection is to create an instance of the SqlConnection class and assign
it to the conn instance. This SqlConnection class is initialized after you pass in the
connection string as a parameter to the class. In this case, you are connecting to
allthe Northwind database that resides on your local machine using the system,
administrator's login credentials,
Another means of making a connection Is to. put the connection string within the
application's web.config file and then 0 make a reference to the web config file,
With ASP.NET 3.5, you will find that there is an easy way to manage the Storage
°F your connection strings ‘through the use of the web.config file. This is actually
@ better way to store your connection strings rather than hard-coding them within
the code of the Application itself, In addition to having a single point in the
application where the credentials for database access can be managed, storing
credentials in the web.config also gives you the ability to encrypt the credentials
To define your connection String within the webséonfig file, you are going to make
Use of the section, From this section, you can place Gri element within it to define
your connection. An example of this is illustrated in Listing 8-6,
Listing 8-6: Providing your connection String Within the web config file
Now that you have a connection string within the web.config file, you can then
make use of that
connection string directly in your code by using the ConnectiontAanager object as
illustrated here in.
Listing 8-7
Listing 8-7: Using the connection string found in the web.config file£e :
conn = New _
SqlConnection( _
ConfigurationManager.ConnectionStrings("DSN_Northwind").ConnectionString)
For this line of code to work, you are going to have to make a reference to the
‘System.Configuration namespace.
When you complete your connection to the data source, be sure that you close the
connection by using conn.Close(). The NET Framework does not implicitly release
«the connections when they fall out
of scope,
Using the Command Object
The Command object uses the Connection obj
queries can be in the form
of inline text, stored procedure
SELECT clause, the resul “
*%@ Import Namespac ="System,Data" %>
<%@ Import Namespace-"System.Data.SqlClient" %>
<%®@ Import Namespace="System.Configuration" %>
mmandBehavior,CloseConnection)piGridView™
Listing 8-8 uses the ‘SqjConnection class to create o connection
“The code shown in
with the Northwind database using the connection string stored in the web.config
| file. This connection string is then retrieved using the'ConfigurationManager
| class. It is always best to store your connection strings inside the web.config and
to reference them in this manner. If you have a single place To work with your
connection strings, any task is a Jot mone Manageable than if you place all your
“connection strings in the actual codesofs your application. After working with the
connection string, this bit, fedde front Listing 8-8 creates a Command object
using the Sqicommand class Becduse You are interested in working with a SQL
database. Next, the code provides ‘the command text, command type. and
connection properties. After the command ‘and the connection ore
created, the code opens the connection and executes the command by calling the
ExecuteReader method of the mycommand object. After receiving the data
reader from the Command obje ply bind the retrieved results To on
ct, you sim
instance of the GridView control. The results are shown in Figure 8-1.pr important tasks, such as reading and writing data to and from an XML file, Zt
didnt even caw you to serialize the DataTable object independently of the larger
"and encompassing DataSet object, This limitation required you to always use the
DataSet object to perform any operation ona DataTable. The current version of
ADONET removes this limitation and enables you to work directly with the
DataTable for all your needs. In fact, we recommend that you don't use the
DataSet object unless you need to work with multiple DataTable objects ond need
a.container object to manage them, If you end up working with only a single table
of information, then it is best to work with an instance of the DataTable object
rather than a DataSet that contains only a single DataTable.
The current version of ADO.NET provides the é€pability to load « DataTable in
memory by consuming a data source using qDataReader, In the past, you were
sometimes restricted to creating multiple overloads ‘Of the same method just to
work with both the DataReader and the DataTable objects. Now you hove the
flexibility to write the data access code ore time and reuse the DataReader —
either directly or to fill o DataTab 705 shown in Listing 8-11.
’ ‘ NF
thie froma DataReader VB
en
Listing 8-11: How to load a\
<%4@ Page Language="VB" %>
<%@ Import Namespace="System Data’ 7
<%@ Import Namespace="System,Data.SqiClient" %>
<%@ Import Namespace="System Configuration” he