AWDT-Unit 4
AWDT-Unit 4
Ado.net is a data access technology that allows interaction between applications and databases. Ado.net is
both connection-oriented as well as disconnection oriented. Depending upon the functionality of an
application, we can make it connection-oriented or disconnection oriented. We can even use both the modes
together in a single application.
The Ado.net framework supports two models of data access architecture.
1. Connected Architecture
2. Disconnected Architecture
1. Connected Architecture
As the name suggests, connected architecture refers to the fact that the connection is established for
the full time between the database and application. For e.g. we make a program in C# that is
connected with the database for the full time, so that will be connected architecture.
Connected architecture is forward only and read-only. This means the connected mode will work
only in one particular direction. Application issues query then read back results and process them.
For connected architecture, we mainly use the object of the DataReader class.
DataReader is used to retrieve the data from the database and it also ensures that the connection is
maintained for the complete interval of time.
In connected architecture, the application is directly linked with the Database.
DataReader class is used to read the data from the database. It works in forward only and reads the
only mode and requires the connection for the complete time. That is why we use it in connected
architecture. The forward only feature makes it an efficient way to read data. Thus we can say,
DataReader is connection-oriented and requires an active connection while reading the data.
1
In order to make an object of the DataReader class, we never use the new keyword instead we call the
ExecuteReader() of the command object. For e.g.
SqlDatareader rdr=cmd.ExecuteReader(cmd);
Here cmd.ExecuteReader() executes the command and creates the instance of DataReader class and
loads the instance with data. Therefore, we do not use the ‘new’ keyword.
2. Disconnected Architecture
Disconnected architecture refers to the mode of architecture in Ado.net where the connectivity
between the database and application is not maintained for the full time. Connectivity within this
mode is established only to read the data from the database and finally to update the data within the
database.
This means during the processing of the application, we need data so that data is fetched from the
database and kept in temporary tables. After that whenever data is required, it is fetched from the
temporary tables. And finally, when the operations were completed, the connection was established
to update the data within the database from the temporary tables.
In this mode, application issues query then retrieves and store results for processing. For this
purpose, we use objects of SqlDataAdapter and DataSet classes.
In disconnected architecture, a Dataset is used for retrieving data from the database. This way there
is no need to establish a connection for the full time because DataSet acts as temporary storage. All
the operations can be performed on the data using the Dataset and finally modified at the database.
2
DataAdapter in Disconnected architecture
DataAdapter class acts as an interface between application and database. It provides the data to the
Dataset which helps the user to perform the operations and finally the modifications are done in the
Dataset which is passed to the DataAdapter which updates the database. DataAdapter takes the
decision for the establishment and termination of the connection.
DataAdapter is required for connectivity with the database. DataAdapter established a connection
with the database and fetches the data from the database and fill it into the Dataset. And finally,
when the task is completed it takes the data from the DataSet and updates it into the database by
again establishing the connection.
It can be said that DataAdapter acts as a mediator between the application and database which allows
the interaction in disconnected architecture.
3
For example:-
In the above lines of code, the object of the SqlDataAdapter is responsible for establishing the connection. It
takes query and ConnectionString as a parameter. The query is issued on the database to fetch the data.
ConnectionString allows connectivity with the database. The fill() of the SqlDataAdapter class adds the
Table.
1. Connection
ADO.NET provides connection to multiple providers. Each provider has a functionality to connect with
different database. Here is a list of data providers in ADO.NET and their purpose.
4
Connection to an ADO.NET Database
Before working with the database, you must import a data provider namespace, by placing the following in
the beginning your code module.
1. Using System.Data.SqlClient
Similarly, for OLE DB, ODBC, OracleClient .NET data provides namespace import code:
1. Using System.Data.OleDb
2. Using System.Data.Odbc
3. Using System.Data.OracleClient
Now, we have to declare a connection string, which is usually defined in the App.Config or Web Config file,
so its availalbe in your application. The typical entry of a connection string is written below:
1. <connectionStrings>
2. <add name="" connectionString="" providerName=""/>
3. </connectionStrings>
Now, if your connection string is pointing to SQL Server database like “EmployeeDataBase”, here os the
connection string with
Establish connection string in Web Config file using the below code:
1. <connectionStrings>
2. <add name="Constr" connectionString="Data Source=
RaviSERVER\RaviSERVER;Initial Catalog= EmployeeDataBase;User ID=sa,pwd=sa123"
providerName="System.Data.SqlClient"/>
3. </connectionStrings>
Now, we create a SqlConnection. We can also pass a connection string direct in the constructor.
Data Source: This identifies the Server name, which could be the local machine, machine domain
name or IP address
Initial Catalog: This identifies the database name.
Integrated Security: When you have started database authentication login with Windows
authentication, Integrated Security specifies Integrated Security=”True” in connection string, else
when you have started the database authentication login with Server authentication Integrated
Security specifies Integrated Security=”false” in the connection string
User Id: Name of the user configured in SQL Server.
Password: Password matching SQL Server User ID.
5
Properties of connection object
Property Description
Command By Command time out, we can get or set number of seconds to wait, while attempting to
Timeout execute a command.
Connection By Connection time out, we can get or set number of seconds to wait for the connection to
Timeout open.
Connection Connection string is used to establish and create connection to data source by using server
String name, database name, user id and password.
Default Database It gets or returns default database name.
Mode By mode property, we can check provider access permission.
Provider By this property, we can get or set provider name.
By this property, we can check your current connection open or close before connection
State
opening or closing
Version This returns the ADO version number.
Method Description
Cancel Cancel an execution.
Close method is used, when any current connection is open and finally it is closed after
Close
completed execution.
Open method is used, if current connection is close then before execution started. First
Open
of all You have opened connection must.
By this method it is used to execute query. Like as Statement, procedure or provider
Execute
provides specific text.
This method invokes, whenever you cancel any changes or any conflict occurs in the
RollBackTransation
current transaction, it ends the current transaction.
If current transaction execution is successfully completed, it ends the current
CommitTransation
transaction.
2.Command
1. The Command Object uses the connection object to execute SQL queries.
2. The queries can be in the Form of Inline text, Stored Procedures or direct Table access.
3. An important feature of Command object is that it can be used to execute queries and Stored
Procedures with Parameters.
4. If a select query is issued, the result set it returns is usually stored in either a DataSet or a
DataReader object.
6
Associated Properties of SqlCommand class
Type of
Property Description
Access
The SqlConnection object that is used by the command object to execute
Connection Read/Write
SQL queries or Stored Procedure.
Represents the T-SQL Statement or the name of the Stored Procedure.
CommandText Read/Write
This property indicates how the CommandText property should be
interpreted. The possible values are:
Property Description
This method executes the command specifies and returns the number of rows affected.
ExecuteNonQuery
The ExecuteReader method executes the command specified and returns an instance of
ExecuteReader SqlDataReader class.
This method executes the command specified and returns the first column of first row
ExecuteScalar of the result set. The remaining rows and column are ignored.
This method executes the command specified and returns an instance of XmlReader
ExecuteXMLReader class. This method can be used to return the result set in the form of an XML document
These are quite often methods in the Command objects. Let us now see each of these with an example
ExecuteNonQuery Method
1. The ExecuteNonQuery method is used to execute the command and return the number of rows
affected.
2. The ExecuteNonQuery method cannot be used to return the result set.
ExecuteReader Method
7
3. The DataReader object cannot be directly instantiated. Instead, we must call the ExecuteReader()
Method of the command object to obtain a valid DataReader object.
ExecuteScalar Method
1. The ExecuteScalar Method in SqlCommandObject returns the first column of the first row after
executing the query against the Data Source.
2. If the result set contains more than one column or rows, it takes only the first column of the first row.
All other values are ignored.
3. If the result set is empty it will return null.
It is best to use ExecuteScalar Method when we use functions like SUM(), COUNT() etc.
ExecuteXmlReader Method
The execute reader method is flexible when we need the result set in the form of an XML document. The
ExecuteXmlReader methods return an Instance of XmlReader class.
3.DataReader
The DataReader Object provides a connection oriented data access to the Data Sources. A Connection
Object can contain only one DataReader at a time and the connection in the DataReader remains open, also
it cannot be used for any other purpose while data is being accessed. When we started to read from a
DataReader it should always be open and positioned prior to the first record. The Read() method in the
DataReader is used to read the rows from DataReader and it always moves forward to a new valid row, if
any row exist.
DataReader.Raed();
Usually we are using two types of DataReader in ADO.NET. They are SqlDataReader and
the OleDbDataReader . The System.Data.SqlClient and System.Data.OleDb are containing these
DataReaders respectively.
8
4.DataAdapter
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter provides the communication between
the Dataset and the Datasource. We can use the DataAdapter in combination with the DataSet Object.
DataAdapter provides this combination by mapping Fill method, which changes the data in the DataSet to
match the data in the data source, and Update, which changes the data in the data source to match the data
in the DataSet. That is, these two objects combine to enable both data access and data manipulation
capabilities.
The DataAdapter can perform Select , Insert , Update and Delete SQL operations in the Data Source.
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.
adapter.Fill(ds);
5.Dataset
It is a collection of data tables that contain the data. It is used to fetch data without interacting with a Data
Source that's why, it also known as disconnected data access method. It is an in-memory data store that can
hold more than one table at the same time. The Dataset contains the copy of the data we requested.
The DataAdapter Object allows us to populate DataTables in a DataSet. We can use Fill method of the
DataAdapter for populating data in a Dataset. The DataSet can be filled either from a data source or
dynamically. A DataSet can be saved to an XML file and then loaded back into memory very easily.
6.CommandBuilder
Sometimes creating SQL statements could be lengthy job when dealing with many columns in a table. A
CommandBuilder object reduces the burden of creating SQL statements for you. In other words, the
9
CommandBuilder helps you to generate update, delete and insert commands on a single database table for a
data adapter. Similar to other objects, each data provider has a command builder class.
We can divide these data presentation controls into the following two main groups.
First of all, we go to the first group that includes the three controls Repeater, DataList and GridView.
For demonstration purposes, we will use a table named StudentDetails in our sample database. Using this
table, we will be able to display our data we stored in the table along with a different control. Let's now take
a detailed look at all of the standard controls used in ASP.NET.
Repeater Control
The ASP.NET Repeater is a basic container control that allows you to create custom lists from any data
available to the page. It provides a highly customized interface. It renders a read-only template; in other
words, it supports only the ItemTemplate to define custom binding.
10
The Repeater control is a Data Bind Control, also known as container controls. The Repeater control is used
to display a repeated list of items that are bound to the control. This control may be bound to a database
table, an XML file, or another list of items.
It has no built-in layout or styles, so you must explicitly declare all layout, formatting and style tags within
the controls templates.
List format
No default output
More control and complexity
Item as row
Paging, Sorting and Grouping requires custom code writing
Only Web control that allows you to split markup tags across the templates
No built-in selection capabilities
No built-in support for edit, insert and delete capabilities
Using the data we stored in table Student of our sample database, the Repeater control will look like this.
DataList Control
DataList is the next step up from a Repeater. DataList allows you to repeat columns horizontally or
vertically. You can configure the DataList control to enable users to edit or delete a record in the table. We
can use a DataList control where we need a single-column list.
The DataList control works like the Repeater control, used to display the data in a repeating structure, such
as a table. It displays data in a format that you can define using a template and styles. However, it arranges
the data defined in the template within various HTML structures.
This includes options for horizontal or vertical layout and it also allows you to set how the data should be
repeated, as flow or table layout. The DataList control does not automatically use a data source control to
edit data.
GridView Control
The GridView control is used to display the values of a data source in a table. Each column represents a
field where each row represents a record. The GridView control provides many built-in capabilities that
allow the user to sort, update, delete, select and page through items in the control. The GridView control can
be bound to a data source control, in order to bind a data source control, set the DataSourceID property of
the GridView control to the ID value of the data source control.
The GridView control offers improvements such as the ability to define multiple primary key fields,
improved user interface customization using bound fields and templates and a new model for handling or
canceling events.
12
Now for the second group. Here is the description of the two controls DetailsView and FormView.
DetailsView control
The DetailsView control uses a table-based layout where each field of the data record is displayed as a row
in the control. Unlike the GridView control, the DetailsView control displays one row from a data source.
The DetailsView supports both declarative and programmatic data binding. The DetailsView control is often
used in master-detail scenarios where the selected record in a master control determines the record to display
in the DetailsView control.
It shows the details for the row in a separate space. We can customize the appearance of the DetailsView
control using its style properties. A DetailsView control appears as a form of recording and is provided by
multiple records as well as insert, update and delete record functions.
Tabular rendering
Supports column layout, by default two columns at a time
Optional support for paging and navigation.
Built-in support for data grouping
Built-in support for edit, insert and delete capabilities
13
FormView control
The FormView control renders a single data item at a time from a data source, even if its data source
exposes a multiple records data item from a data source. It allows for a more flexible layout when displaying
a single record.
The FormView control renders all fields of a single record in a single table row. In contrast, the FormView
control does not specify a pre-defined layout for displaying a record. Instead, you create templates that
contain controls to display individual fields from the record.
A FormView is a databound control used to insert, display, edit, update and delete data in ASP.NET that
renders a single record at a time. A FormView control is similar to a DetailView in ASP.NET but the only
difference is that a DetailsView has a built-in tabular rendering whereas a FormView requires a user-defined
template to insert, display, edit, update and delete data.
Template driven
Supports column layout
Built-in support for paging and grouping
Built-in support for insert, edit and delete capabilities
14