Sie sind auf Seite 1von 21

M11.1: What is ADO.

NET:
Most applications handle data, whether in the form of a database, text file,
spreadsheet, whatever the majority of modern day programs need access to an
information store. ADO.NET technology fulfills these needs for .NET programs.
ADO.NET is the new database technology of the .NET platform, and it builds on ADO
(ActiveX Data Objects). 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.
ADO.NET brings along with it four, much-publicized advantages:
Interoperability - All data in ADO.NET is transported in XML format, meaning it's
simply a structured text document that can be read by anyone on any platform.
Scalability - The client/server model is out. ADO.NET promotes the use of
disconnected datasets, with automatic connection pooling bundled as part of the
package.
Productivity - You can't just pick it up and run, but ADO.NET can certainly improve
your overall development time. For example, "Typed DataSets" help you work quicker
and produce more bug-free code.
Performance - Because ADO.NET is mainly about disconnected datasets, the
database server is no longer a bottleneck and hence applications should incur a
performance boost.
For the past several years, ADO.NET has been one of the primary technologies for
connecting to a database with .NET applications. It offers a high level of abstraction,
allowing a more object oriented approach to working with data than was possible
with earlier data access technologies. With ADO.NET, a program can view, insert,
update, and delete database records. It supports both a connected and disconnected
model.
First, lets take a look at ADO.NET architecture.
Page 1

www.magix.in

M11.2: ADO.NET Architecture:


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 consists of a set of Objects that expose data access
services to the .NET environment. Data Access in ADO.NET relies on two components:
DataSet and Data Provider.

DataSet:
Once we've created a connection to the database and retrieved data from it, we can
manipulate that data within our program using a DataSet object. The DataSet
contains a collection of DataTable objects, and any relations between them. A
DataTable - as its name suggests - stores data in a tabular format; that is, in columns
and rows. It can be considered as a local copy of the relevant portions of the
database. Because the DataSet doesn't form part of the data provider (there's only
one type of DataSet object, regardless of whether the data comes from SQL Server,
or an OLE DB data source), the DataSet doesn't maintain a connection to the data
source. This means that when we manipulate data in a DataSet, we're just working
with a copy of the data in memory on the local machine. This eases the strain on the
database server and on the network, because we only connect to the data source
when we first get the data, and when we've finished editing it and want to upload our
changes back to the 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 data provider consists of a number of data source-specific components that
allow us to connect to and communicate with individual data sources. Each data
provider resides in its own namespace within the System.Data namespace. At the
time of writing, there are five data providers available:
The data provider for SQL Server- This resides in the System.Data.SqlClient
namespace, and is used to connect to SQL Server 7.0 or greater and MSDE
databases (MSDE is a cut-down version of SQL Server). The SQL Server provider
is shipped as part of the .NET Framework. If you need to connect to a SQL
Server 6.5 or earlier database, you will need to use the OLE DB provider.
The data provider for OLE DB- This is used to connect to data sources through
OLE DB and resides in the System.Data.OleDb namespace. Like the SQL
Server provider, it also ships with the .NET Framework. The OLE DB provider
cannot be used to connect to databases through ODBC drivers.
Page 2

www.magix.in

The data provider for ODBC- The ODBC provider can be used to connect to
databases which have ODBC drivers. The ODBC data provider namespace is
Microsoft.Data.Odbc.
The data provider for ORACLE- This resides in the System.Data.Oracle
namespace, and is used to connect to Oracle database server.
The BORLAND data provider- This resides in the System.Data.Bdp
namespace, and is used to Generic access to many databases such as
Interbase, SQL Server, IBM DB2, and Oracle.
Each DataProvider consists of the following component classes:
Component
Description
Name
Connection
Used to connect to a database or other data source.
Command
Used to retrieve, edit, delete, or insert data in the
database.
DataReader
Provides a stream of data from the data source. This
data can only be read (it can't be modified), and we can
only move forwards through the data.
DataAdapter
populates a disconnected DataSet with data and
performs update.

(M11.1: Architecture of ADO.NET)


Page 3

www.magix.in

M11.3: Connected & Disconnected Database:


The ADO.NET Framework supports two models of Data Access Architecture,
Connection Oriented Data Access Architecture and Disconnected Data Access
Architecture.
In Connection Oriented Data Access Architecture the application makes a connection
to the Data Source and then interacts with it through SQL requests using the same
connection. In these cases the application stays connected to the database system
even when it is not using any Database Operations. As applications become more
complex and databases begin to serve more and more clients, a connected data
access technology becomes impractical for a variety of reasons. For example:
Open database connections are expensive in terms of system resources. The
more open connections, the less efficient system performance becomes.
Applications with connected data access are very difficult to scale up. An
application that can maintain connections with two clients might do poorly with
10, and might be completely unusable with 100.
ADO.NET addresses these issues by implementing a disconnected database access
model by default. This means that when you receive the data from the database, the
result is stored on your local machine. You can then manipulate the result locally,
and only connect to the database when you wish to update it or get new results. This
eases the strain on the database server and on the network, because we only
connect to the data source when we first get the data, and when we've finished
editing it and want to upload our changes back to the database.
In ADO.NET, the DataSet and Data Adapter objects enable disconnected mode
operations. Data Adapters are instrumental for disconnected mode by managing the
connection. When retrieving data from the database, the Data Adapter opens a
connection, fills the specified DataSet, and then automatically closes the connection
as soon as the data is read. After youve made changes to the data, you use the Data
Adapter again to open the connection, persist changes (whether they are add,
update, or delete), and automatically close the connection.
However, with the advantages of a disconnected architecture there also come
problems. When in a completely disconnected environment, the user is not notified
of data changes made by other users. Therefore, if we use the data we see on the
screen to make decisions, we may have out-of-date information if other users are
editing the same data.
Following table summarizes some of the main differences between connected and
disconnected data access architecture:

Page 4

www.magix.in

Connected Data Access


1. Continuous connection to data source
is required to do any operation.

1.

2. Only one operation can be performed


at a time in connected environment.

2.

3. DataReader is used in connected


environment.
4. Connected environment is slower in
speed.
5. We always get updated data in
connected environment.
6. Difficult to scale up and more data
consumers we add the more
performance degradation will happen.

3.
4.
5.
6.

Disconnected Data Access


Connection to data source is only
required at the time of retrieving or
updating the data.
Multiple operations can be performed
at a time while connection is active to
data source.
DataSet is used in disconnected
environment.
Disconnected environment has a good
speed.
In disconnected environment, there is
a problem of dirty read.
Scaling is comparatively easy and
more data consumers can be
attached to database with a little
performance degradation.

ADO.NET makes it easy to manage data in a disconnected mode; it isnt the recommended
solution for all problems. Youll have to make a design decision, based on your application
requirements, as to whether working with disconnected mode is more of a benefit than
connected mode. If you need data persisted to the database immediately, use connected
mode. However, if you have isolated data that no one else will change or the data rarely
changes, maybe your analysis will reveal that disconnected mode has a benefit in your
situation.

M11.4: Creating Connection using ADO.NET:


In most cases when working with data and ADO.NET, you will need to establish a
connection to the data source. This data source can be SQL server 2000, SQL server 2005,
SQL server 2010, Oracle, Microsoft Access, or any number of other types of data including
file-type sources such as Paradox files or even Microsoft Excel documents.
But before discussing, how we connect and make use of a data source; we should first
discuss the ADO.NET object model first, then some of the important classes in detail. It will
help us to understand the inner class and object structure of ADO.NET concept. Then it will
be little easy to use it.

M11.4.1: ADO.NET Object Model:


ADO.Net programming is all about objects... and how to knit the objects together The ADO.NET
object model consists of two key components as follows:

Connected model (.NET Data Provider - a set of components including the


Connection, Command, DataReader, and DataAdapter objects):
we have the control over the database connection, so we have to explicitly
open/close...the objects in model have to directly talk to the database and hence are
database specific Connection, Command and Data Reader are members of this set.
Page 5

www.magix.in

Disconnected model (DataSet):


Its complimentary to earlier model in the sense that the object itself decides when
the connection will be opened and closed...we dont have to do it implicitly...as a
result only one component of this model which talks to the database directly is data
adapter ...whereas the cache which contains the data never speaks to the database
directly and isnt database specific.

The basis of the ADO.Net object model is shown below:

The same diagram with detail structure can be shown as:

Page 6

www.magix.in

Here's a list of the most common ADO.NET objects:


Data connection objectsTo 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.
Data adaptersData 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 execute against the data source.
Command objectsData adapters can read, add, update, and delete records in a
data source. To allow you to specify how each of these operations work, a data
adapter contains command objects for each of them. Data adapters support four
properties that give you access to these command objects: SelectCommand,
InsertCommand, UpdateCommand, and DeleteCommand.
DatasetsDatasets 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.
DataTable objectsDataTable objects hold a data table from a data source. Data
tables contain two important properties: Columns, which is a collection of the
DataColumn objects that represent the columns of data in a table, and Rows, which
is a collection of DataRow objects, representing the rows of data in a table.
Data readers DataReader objects hold a read-only, forward-only (i.e., you can only
move from one record to the succeeding record, not backwards) set of data from a
database. Using a data reader can increase speed because only one row of data is in
memory at a time.
Data viewsData views represent a customized view of a single table that can 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 objectsDatasets support constraints to check data integrity. A constraint,
supported by the Constraint class, is a 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 in a column are
unique throughout the table, and foreign-key constraints specify how related records
should be updated when a record in another table is updated.

Page 7

www.magix.in

DataRow objectsDataRow 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.
DataColumn objectsDataColumn objects correspond to the columns in a table.
Each object has a DataType property that specifies the kind of data each column
contains, such as integers or string values.
DataRelation objectsDataRelation objects specify a relationship between parent
and child tables, based on a key that both tables share.

An application can access data either through a dataset or through a


datareader object:
Using a dataset: In this case, the data is cached in a dataset and
the application accesses the data from the dataset.
Using a datareader: In this method, a datareader object, which is
a component of the data provider, uses the connection object to
connect to the database, uses the command object to retrieve
data, and provides data to the application in a read-only and
forward-only mode.

M11.4.2: The Connection Class:


The Connection class is provided by all standard ADO.NET providers and represents
a connection between your code and a data source. Connections require resources,
so one hallmark of well-written ADO.NET code is that it opens a connection only when
necessary and releases it as soon as possible.
Most of the Connection properties are informational and can't be modified directly.
Instead, before opening a connection, you use the ConnectionString property to set
such information as the location of the data source, the authentication credentials,
and the connection timeout. The Connection class is also the heart of client-side
transactions with ADO.NET, connection pooling, and schema tables with the OLE DB
provider. Following figure shows the relationship between a connection, a data
source, and a data adapter:

Page 8

www.magix.in

Each data provider has a Connection class. Below Table shows the name of various
connection classes for data providers.
Table: Data provider connection classes
Data Provider
1.
2.
3.
4.

OldDB
Sql
ODBC
Oracle

1.
2.
3.
4.

Connection Class
OleDbConnection
SqlConnection
OdbcConnection
OracleConnection

As from upper discussion, you probably know that for a connection we first need to
set a connection string. Many things can go into a connection stringdepending, of
course, upon the provider and configuration. Connection String is a normal String
representation which contains Database connection information to establish the
connection between Database and the Application. The Connection String includes
parameters such as the name of the driver, Server name and Database name, as
well as security information such as user name and password. Data providers use
a connection string containing a collection of parameters to establish the connection
with the database. Lets have some examples:
Microsoft SQL Server Connection String
connetionString ="Data Source = ServerName; Initial Catalog = Databasename; User
ID = UserName; Password=Password"
OLEDB Data Provider Connection String
connetionString = "Provider = Microsoft.Jet.OLEDB.4.0;
yourdatabasename.mdb;"
ODBC Connection String
connetionString = "Driver = {Microsoft Access
yourdatabasename.mdb;"

Driver

Data

Source

(*.mdb)};

DBQ

Note: You have to provide the necessary information to the Connection String attributes.

When you have a connection string, youre ready to connect to your data source. A
connection represents a live connection to the data source. Before seeing the code to
establish a database connection, you should be aware of the cost of connections. As
a general rule of thumb, database connections are expensive, and acquiring new
connections can be costly both in terms of time and resources.
To help alleviate this, many data providers support the notion of connection pooling.
When pooling is used, connections are placed in a pool when they are first created.
When a pooled connection is closed, it is returned to the pool instead of being
Page 9

www.magix.in

completely destroyed. The next time your application requests a database


connection with the same connection string, the data provider can then retrieve the
previously created connection from the pool at a much lower cost than creating one
from scratch.
Lets have our first example of creating a connection. We are going to use the
Northwind database in our examples.
First, import the "System.Data.OleDb" namespace. We need this namespace to work
with Microsoft Access and other OLE DB database providers. We will create the
connection to the database in the Page_Load subroutine. We create a dbconn
variable as a new OleDbConnection class with a connection string which identifies
the OLE DB provider and the location of the database. Then we open the database
connection:
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
sub Page_Load
dim dbconn
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
data source=" & server.mappath("northwind.mdb"))
dbconn.Open()
end sub
</script>
Note: The connection string must be a continuous string without a line break!

M11.4.3: The Command Class:


The Command class is provided by all standard ADO.NET providers, and it almost always
encapsulates a SQL statement or a stored procedure call that can be executed against a
data source. Command objects can retrieve rows; directly insert, delete, or modify records;
calculate totals and averages; alter the structure of a database; or fill a disconnected
DataSet when used with a DataAdapter.
At a bare minimum, every Command must reference a Connection object, which it uses to
communicate with the data source and define a few key properties, such as
CommandText(the stored procedure or embedded SQL command) and CommandType. The
Command class is provided in several provider-specific varieties, including SqlCommand
and OleDbCommand.
To execute a Command, you use one of the Command object methods, including
ExecuteNonQuery( ), ExecuteReader( ), and ExecuteScalar( ), depending on the type of
Command. Occasionally, a provider may define an additional method, such as the
ExecuteXmlReader( ) method offered by the SQL Server provider, which retrieves query
results as an XML document. Other than this discrepancy, the Command objects provided
by the core set of ADO.NET providers are virtually identical.
Page 10

www.magix.in

Command objects commonly 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 (return first column of the
first row in the resultset.)
ExecuteReader:
Returns a result set by way of a DataReader object
Lets have a simple code snippet to show how this works:

SqlCommand myCommand = myConnection.CreateCommand();


//this code is from MSDN with a little change
myCommand.CommandText = "select count(*) as NumberOfRegions from region";
int count = (int) myCommand.ExecuteScalar();

M11.4.4: The DataReader Class:


The DataReader object represents a read-only, forward-only stream of data, which is
ideal for quickly retrieving query results. Best of all, because the DataReader loads
only a single row into memory at a time, it has a small in-memory footprint.
You can't create a DataReader directly. Instead, you must use the ExecuteReader( )
method of a Command object that returns a DataReader.
Imagine these lines of code in a console application:
// create connection object for Microsoft Access OLE DB Provider
OleDbConnection myConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data Source=C:\Test.MDB");
// open connection object
myConnection.Open();
// create SQL command object on this connection
OleDbCommand myCommand = myConnection.CreateCommand();
// initialize SQL SELECT command to retrieve desired data
myCommand.CommandText = "SELECT Column1 FROM Table1";
// create a DataReader object based on previously defined command object
OleDbDataReader myReader = myComman\d.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine("{0}", myReader["Column1"]);
}
myReader.Close();
myConnection.Close();

The output of this code is all rows of column1 from table1.Don't forget to close both
Connection and DataReader at the end of your operations.
Page 11

www.magix.in

M11.4.5: The DataAdapter Class:


The DataAdapter class serves as a bridge between a DataSet and a data source. The
DataAdapter both retrieves a DataSet from a data source and updates any changes
made to the DataSet back to the data source.
DataAdapter has several methods associated with it. Most commonly used methods
among them are listed below:
Fill: Fill method is used to fetch records from the database and update them
into the datatables of dataset. Uses SelectCommand for execution. Syntax for
Fill method is :
sampleAdapter.Fill(employeeset,Employee);
Here sampleAdapter is a SqlDataAdapter containing select query for Employee,
employeeset is the dataset and Employee is the database table.
FillSchema: FillSchema method is used to create an empty table in dataset
containing the same schema as that of a specific table in the database.
Constraints of the corresponding database table is also copied and reflected in
the datatable of dataset. Uses SelectCommand for execution but copies only
the schema of the table and not the data. Syntax for this method is shown
below:
sampleAdapter.FillSchema(empDataSet, SchemaType.Source, "Employee");
Here empDataSet is the dataset and Employee is the database table name.
Update: Manipulated records of the dataset are updated back in the database
using this method. Records that are inserted, updated and deleted from the
dataset are pushed into the database using this method. Uses InsertCommand
or UpdateCommand or DeleteCommand for the above mentioned purpose.
Syntax for Update method is shown below:
sampleAdapter.Update(employeeTable);
Before this statement, sampleAdapter will include an UpdateCommand.
employeeTable is the datatable of the dataset.
Dispose: This method is used to release all resources used by the dataadapter.
Here is the syntax:
sampleAdapter.Dispose();

Page 12

www.magix.in

Dataadapters are used for two main purposes. They are listed below:
To fetch data from the database and display them in the datatables of dataset.
This is achieved using Fill method of dataadapter.
To fetch data from dataset and update them in necessary tables of database.
This is achieved using Update method of dataadapter.
There are four different types of Dataadapters. Their purpose and usage is mentioned
below:
OleDbDataAdapter: Dataadapters used to interact with databases through OLE
DB provider. It belongs to System.Data.OleDb namespace.
SqlDataAdapter: Dataadapters used to interact with SQL Server database with
version 7.0 or higher through Tabular data services. It belongs to
System.Data.SqlClient namespace.
OdbcDataAdapter: Dataadapters used to interact with databases exposed by
an ODBC provider. It belongs to System.Data.Odbc namespace.
OracleDataAdapter: Dataadapters used to interact with Oracle database. It
belongs to System.Data.OracleClient namespace.
Dataadapter has four different properties which controls database updates. The
properties are SelectCommand, UpdateCommand, InsertCommand and
DeleteCommand. These commands are used to read, update, add and delete
records from a database respectively.
//Create an instance of a OleDbDataAdapter
//by passing OleDbConnection object and select.. query
OleDbDataAdapter dAdapter = new OleDbDataAdapter ("select * from PersonTable", con );

//fill the DataSet with records from the table "PersonTable"


dAdapter.Fill(dSet, "PersonTable");

M11.4.6: The DataSet Class:


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. As with all disconnected data classes, the DataSet isn't
specific to any data provider.
The structure of a System.Data.DataSet is similar to that of a relational database. It
is organized in a hierarchical object mode of tables, rows, columns, constraints, and
relationships.
Page 13

www.magix.in

The DataSet object is made up of two objects:


DataTableCollection object containing null or multiple DataTable objects
(Columns, Rows, Constraints).
DataRelationCollection object containing null or multiple DataRelation
objects which establish a parent/child relation between two DataTable
objects.
//Create a DataSet
DataSet dset = new DataSet();
There are two types of DataSets:
1. Typed DataSet
2. Untyped DataSet
1. Typed dataset is similar to a dataset with only difference is that the schema is
already present in typed dataset. So if any mismatch in the column will
generate compile time errors rather than runtime error as in the case of
normal dataset. Also accessing the column value is much easier than the
normal dataset as the column definition will be available in the schema
Example: Let us look into a small example which explain the Typed DataSet,
1. Using DataSet:
//Create DataAdapter
SqlDataAdapter daEmp = new SqlDataAdapter("SELECT empno, empname,
empaddress FROM EMPLOYEE",conn);
//Create a DataSet Object
DataSet dsEmp = new DataSet();
//Fill the DataSet
daEmp.Fill(dsEmp,"EMPLOYEE");
//Let us print first row and first column of the table
Console.Write(dsEmp.Tables["EMPLOYEE"].Rows[0][0].ToString());
//Assign a value to the first column
dsEmp.Tables["EMPLOYEE"].Rows[0][0] = "12345";//This will generate runtime error
as empno column is integer

If we observe above code we will get a runtime error when this code gets
executed as the value assigned to the column (empno) does not take string
value.
Page 14

www.magix.in

2. Using Typed DataSet:


//Create DataAdapter
SqlDataAdapter daEmp = new SqlDataAdapter("SELECT empno, empname,
empaddress FROM EMPLOYEE",conn);
//Create a DataSet Object. Note that an instance of the EmployeeDS class is
//created: the class that maps to the EmployeeDS Schema and inherits from
//the DataSet class, not the generic DataSet class itself.
EmployeeDS dsEmp = new EmployeeDS( );
//Fill the DataSet
daEmp.Fill(dsEmp,"EMPLOYEE");
//Let us print first row and first column of the table
Console.Write(dsEmp.EMPLOYEE[0].empno.ToString());
//Assign a value to the first column
dsEmp.EMPLOYEE[0].empno = "12345"; //This will generate compile time error.

If we see above code, a typed dataset is very much similar to a normal dataset.
But the only difference is that the schema is already present for the same.
Hence any mismatch in the column will generate compile time errors rather
than runtime error as in the case of normal dataset. Also accessing the column
value is much easier than the normal dataset as the column definition will be
available in the schema.
Note: We will soon learn how to create a typed dataset.

2. An Untyped dataset is not defined by a schema, instead, you have to add


tables, columns and other elements to it yourself, either by setting properties
at design time or by adding them at run time. Typical scenario: if you don't
know in advance what the structure of your program is that is interacting with a
component that returns a DataSet.
//Create DataAdapter
SqlDataAdapter daEmp = new SqlDataAdapter("SELECT empno, empname,
empaddress FROM EMPLOYEE",conn);
//Create a DataSet Object
DataSet dsEmp = new DataSet();
//Fill the DataSet
daEmp.Fill(dsEmp,"EMPLOYEE");
//Let us print first row and first column of the table
Console.Write(dsEmp.Tables["EMPLOYEE"].Rows[0][0].ToString());
//Assign a value to the first column
dsEmp.Tables["EMPLOYEE"].Rows[0][0] = 12345 ;

Page 15

www.magix.in

DataSets are memory structures that do not contain any data by default. DataSets
will have to be filled with data. This can be done in several ways.
1) By calling the Fill method of DataAdapter. For example:
//Create DataAdapter
SqlDataAdapter
daEmp
=
new
SqlDataAdapter("SELECT
empno,
empname,empaddress FROM EMPLOYEE",conn);
//Create a DataSet Object
DataSet dsEmp = new DataSet();
//Fill the DataSet
daEmp.Fill(dsEmp,"EMPLOYEE");
2) Manually populate the DataSets by creating DataRow objects and call the
AddNew method. For example:
DataSet dset;
DataTable dtbl;
DataRow drow;
//create a new row
drow=dtbl.NewRow();
//manipulate the newly added row using an index or the column name
drow["LastName"]="Altindag";
drow[1]="Altindag";
//After data is inserted into the new row, the Add method is used
//to add the row to the DataRowCollection
dtbl.Rows.Add(drow);
//You can also call the Add method to add a new row by passing in an
//array of values, typed as Object
dtbl.Rows.Add(new object[] {1, "Altindag"});
3) Read an XML Document or stream into the dataset.
4) Copy the contents of one DataSet with another.
5) Copy the contents of one DataTable into a DataSet
A DataSet can store not only the data but also information about the data such as
original, modified, inserted and deleted. Update of the underlying data-store is also
possible. This can be done by calling the Update method of the TableDataAdapter
or DataAdapter.
Page 16

www.magix.in

1.

2.
3.
4.
5.

Strongly Typed DataSet


It provides additional methods,
properties and events and thus it
makes it easier to use.
You will get type mismatch and other
errors at compile time.
You will get advantage of intelliSense
in VS. NET
Performance is slower in case of
strongly typed dataset.
In complex environment, strongly
typed dataset's are difficult to
administer.

Untyped DataSet
1. It is not as easy to use as strongly
typed dataset.
2. You will get type mismatch and other
errors at runtime.
3. You can't get an advantage of
intelliSense.
4. Performance is faster in case of
Untyped dataset.
5. Untyped datasets are easy to
administer.

How to Generate Typed DataSet? :


A Typed DataSet can be generated in two ways:
1. Using Visual Studio .NET IDE.
2. Using XSD.exe (Using VS.Net command prompt)
Open VS.Net command prompt and Type XSD /? For the help on this exe.

Creating a Typed DataSet using Visual Studio .NET IDE


Follow these steps to create a small Web application by using Visual Studio .NET. The
Web application uses a typed DataSet to display the results of an improvised SQL
query in the Northwind database.
1. Start Visual Studio .NET.
2. Create a new Web Application project named TDS in Visual C# .NET.
3. Make sure that the Default.aspx page is open in the Editor window. If the page is not
open, double-click Default.aspx in the Solution Explorer to open the page.
4. Under the Editor window, click Design to switch to Design view.
5. To open the toolbox, press CTRL+ALT+X. In the toolbox, click Web Forms. Select and
drag the following to the upper-left corner of the page: two rows each of a label followed
by a text box (positioned to the right of each label). Under these, add a GridView in the
same way.

Page 17

www.magix.in

6. Click the top label. Press F4 to display the Properties window. Change the Text property to
Title. Click the other label, and then change its Text property to YearReleased.
7. To add a new DataSet to the project, press CTRL+SHIFT+A, and then click DataSet in the list of
templates. Name the DataSet the following: dsProducts.xsd. Click Ok. Visual Studio will
recommend placing the DataSet file inside the App_Code folder, which you should allow it to
do for you. Note that the file is actually an XML Schema.
8. The dsProducts.xsd will open in design mode, and the TableAdapter Configuration Wizard
will launch. For now, just click Cancel, as we will add tables by dragging them from the Server
Explorer.
9. To create a typed DataSet, press CTRL+ALT+S to open the Server Explorer. We can start
designing the dataset. Now defining the dataset can be done in two ways,
A. Using the tool box
B. Using the server explorer

10. Here we will use the second method. Now the first thing we must do is to Add a new
Data Source to our project

To add a Data Source:


a.

In Server Explorer right click on Data Connection Select New Connection.


This displays the Add Connection dialog window.
b.Enter the information to connect to your instance of SQL Server or MSDE and the
DVDCollectionDatabase.mdf. (Generally this sample database file will be under structure
C:\Program files\ Microsoft Visual Studio8\Common7\IDE\ ProjectTempaltesCache\ CSharp\
Starter Kits\1033\ MovieCollection.zip\ DVDCollectionDatabase.mdf)

c.
d.
e.
f.

g.
11.

Select OK to dismiss the dialog.


Select Next. This displays the Choose Your Database Objects page.
Note that you can choose from Tables, Views, Stored Procedures, or
Functions.
Expand the Tables node and select the DVDs table. We will use all of the
columns in the table, but you can select only those columns that you need for your
application.
Select Finish to exit the wizard.

Drag the DVDs tables to your DataSet Designer window. The window should now resemble the screen
shot below. What are we looking at? For each table we added, Visual Studio created a strongly typed
DataTable (the name is based on the original table) and a TableAdapter. The DataTable has each
column defined for us. The table adapter is the object we will use to fill the table. By default we have a
Fill() method that will find every row from that table.

Page 18

www.magix.in

12. By default it will have a TableAdapter (DVDsTableAdapter here) with Fill() and GetData()
methods that can be used to fill and fetch data from the database without implementing a
line of code.
13. To write code to display the typed DataSet, double-click directly on the Web Form (not on a
Web Control). The Web Form's codebehind appears, and the insertion point is inside the
Page_Load event.
14. In the Page_Load event procedure, create a Connection object by passing the connection
string to the default constructor of the SqlConnection class:
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Program
Files\Microsoft
Visual
Studio
8\Common7\IDE\ProjectTemplatesCache\CSharp\Starter
Kits\1033\MovieCollection.zip\DVDCollectionDatabase.mdf;Integrated Security=True;User Instance=True");

15. Create a SqlCommand object that is then passed to the SqlDataAdapter object. Pass an
improvised SQL statement and the new Connection object to the SqlCommand constructor.
The former sets the CommandText property of the new SqlCommand object. You can also
pass the name of a stored procedure.
SqlCommand cmd = new SqlCommand("select * from DVDs", con);

16. Create an instance of the SqlDataAdapter object, passing the new SqlCommand object
to the constructor:
SqlDataAdapter sda = new SqlDataAdapter(cmd);
17. Now you create the objects that are required to connect to the database and return data. The
following is the code for the typed DataSet. Note that an instance of the dsProducts class is
created: the class that maps to the dsProducts Schema and inherits from the DataSet class,
not the generic DataSet class itself.

dsProducts tds = new dsProducts( );


18. Call the Fill method of the SqlDataAdapter, passing in the typed DataSet object and the
DataSet's typed DataTable TableName property:

sda.Fill(tds, DVDs);
19. To set the Text property of the text box controls to the strongly typed columns in the typed
DataSet's DataTable, use the following format:

tds.DataTableName[RowIndex].ColumnName
For this sample application, the RowIndex is hard-coded to 5:
TextBox1.Text = tds.DVDs[5].Title;
TextBox2.Text = tds.DVDs[5].YearReleased;
Because the Rows collection is zero-based, when the page loads, note that the text box
controls display the product and category names of the item in the sixth row of the GridView.

20. To display all of the results in the GridView1, set the DataSource property of the
GridView1 to the new typed DataSet, and call DataBind():
GridView1.DataSource = tds;
GridView1.DataBind( );
Page 19

www.magix.in

Complete Code Listing (Default.aspx):


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE
html
PUBLIC
"-//W3C//DTD
XHTML
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

1.0

Transitional//EN"

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Title"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Releasing Year"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>

Complete Code Listing (Default.aspx.cs):


public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
dsProducts tds = new dsProducts();
SqlConnection
con
=
new
SqlConnection(@"Data
Source=.\SQLEXPRESS;
AttachDbFilename=D:\Program
Files\Microsoft
Visual
Studio
8\
Common7\
IDE\
ProjectTemplatesCache
\CSharp
\Starter
Kits\
1033\MovieCollection.zip
\DVDCollectionDatabase.mdf; Integrated Security=True;User Instance=True");

SqlDataAdapter sda = new SqlDataAdapter("select * from DVDs", con);


sda.Fill(tds, "DVDs");
TextBox1.Text = tds.DVDs[5].Title;
TextBox2.Text = tds.DVDs[5].YearReleased;
GridView1.DataSource = da;
GridView1.DataBind();
}
}
Page 20

www.magix.in

A DataSet is typically a disconnected data-store. It does not support the idea of a


current record. All the records in the DataSet are available at any time. You can
access any row at any time directly. If the data is bound to one or more controls you
can use the BindingNavigator to traverse the records.
Dataset and Datareader are the two main objects of ADO.NET that are used to read and
manipulate data from data store. Differences between them are tabulated below:
Data Set
Data Reader
1. The data store whose records have to
1. You can read data from datareader
be manipulated can be disconnected.
only if the connection to data store
exists.
2. You have the provision to cache data
2. Caching of data is not possible.
fetched from data store when using
dataset.
3. Dataset objects have XML Support.
3. XML Support is not provided by
datareader.
4. A single dataset object can contain
4. Datareader can read records fetched
collection of datatable objects
by a command object containing a
wherein each datatable object refers
single query. If you have to fetch data
to a table in the datastore. Hence
from multiple tables, then datareader
you can manipulate on multiple tables
is not advantageous when compared
using a dataset.
to dataset.
5. Using dataset, you can read the
5. While reading records, you can iterate
records fetched in any order.
only in forward direction.
6. Performance wise, dataset is slow
6. Datareader gives high performance
because it has multiple tables which
and records can be fetched faster
in turn include multiple rows, columns
when compared to dataset.
and constraints.

Now we know something about ADO.NET and how to use it. We will use this concept
with .NET controls to manipulate them. See ya in the next chapter.

Conclusion:
This chapter has touched a very big topic: ADO.NET database connectivity. The bad
news is that this topic alone is way too vast to be covered in a single chapter. The
good news is the material in this chapter will help point you in the right directions for
your own applications.

Page 21

www.magix.in

Das könnte Ihnen auch gefallen