Unit IV
Unit IV
Unit IV
NET Notes
Architecture of ADO.NET:
The .NET Framework Data Providers are components that have been 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 that were made to the data in the DataSet back to
the data source.
The full form of ADO.NET is ActiveX Data Object.Net. Basically it is container of
all the standard classes which are responsible for database connectivity of .net
application to the any kind of third party database software like Ms Sql Server, Ms
Access, MySql, Oracle or any other database software.
All classes belongs to ADO.NET are defined and arrange in “System.Data” namespace.
The architecture of ADO.NET is following.
From above diagram it is clear that ADO.NET contain following important components. 1.
Connection
2. Command
3. DataReader
4. DataAdapter
5. Dataset
1. Connection: This component of Ado.net is responsible to connect our .net application with
any data source like Ms sql server database.
2. Command: This component contain classes for executing any INSERT, UPDATE, DELETE AND
SELECT command over database software using active connection.
Page|1
UNIT 4 ASP.NET Notes
3. DataReader: This component contains classes that capable to hold reference of records that
retrieved by Command class after executing SELECT Query.
4. Data Adapter: This component is capable to perform the entire task like executing INSERT,
UPDATE, DELETE and SELECT command on give Connection. The most important use of this
component is executing SELECT query for a number of records and fill up to Dataset components.
5. Dataset: This component is the main source of records for .net control like GridView. It has
capability to generate a number of tables to hold records retrieved from DataAdapter or XML.
The .NET Framework provides the following data providers that we can use in our
application.
.NET Framework Data Provider for It provides data access for Microsoft SQL Server. It requires
SQL Server the System.Data.SqlClient namespace.
.NET Framework Data Provider for It is used to connect with OLE DB. It requires
OLE DB the System.Data.OleDb namespace.
.NET Framework Data Provider for It is used to connect to data sources by using ODBC. It
ODBC requires the System.Data.Odbc namespace.
.NET Framework Data Provider for It is used for Oracle data sources. It uses
Oracle the System.Data.OracleClient namespace.
EntityClient Provider It provides data access for Entity Data Model applications. It
requires the System.Data.EntityClient namespace.
Page|2
UNIT 4 ASP.NET Notes
.NET Framework Data Provider for It provides data access for Microsoft SQL Server Compact
SQL Server Compact 4.0. 4.0. It requires the System.Data.SqlServerCe namespace.
• Managing connection
• Selecting data
• Managing presentation aspects like paging, caching, etc.
• Manipulating data
There are many data source controls available in ASP.NET for accessing data from
SQL Server, from ODBC or OLE DB servers, from XML files, and from business
objects.
Based on type of data, these controls could be divided into two categories:
Page|3
UNIT 4 ASP.NET Notes
Page|4
UNIT 4 ASP.NET Notes
The following code snippet shows a data source control enabled for data
manipulation:
<asp:SqlDataSource runat="server" ID= "MySqlSource"
ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName %>'
ConnectionString=' <%$ ConnectionStrings:LocalNWind %>'
SelectCommand= "SELECT * FROM EMPLOYEES"
UpdateCommand= "UPDATE EMPLOYEES SET LASTNAME=@lame"
DeleteCommand= "DELETE FROM EMPLOYEES WHERE EMPLOYEEID=@eid"
FilterExpression= "EMPLOYEEID > 10">
.....
.....
</asp:SqlDataSource>
public Student()
Page|5
UNIT 4 ASP.NET Notes
{}
dt.Columns.Add("StudentID", typeof(System.Int32));
dt.Columns.Add("StudentName", typeof(System.String));
dt.Columns.Add("StudentCity", typeof(System.String));
dt.Rows.Add(new object[] { 1, "M. H. Kabir", "Calcutta" });
dt.Rows.Add(new object[] { 2, "Ayan J. Sarkar", "Calcutta" });
ds.Tables.Add(dt);
return ds;
}
}
Take the following steps to bind the object with an object data source and retrieve
data:
• Create a new web site.
• Add a class (Students.cs) to it by right clicking the project from the Solution
Explorer, adding a class template, and placing the above code in it.
• Build the solution so that the application can use the reference to the class.
• Place an object data source control in the web form.
• Configure the data source by selecting the object.
Page|6
UNIT 4 ASP.NET Notes
• Place a data bound control such as grid view on the page and select the
object data source as its underlying data source.
• At this stage, the design view should look like the following:
• Run the project, it retrieves the hard coded tuples from the students class.
Page|7
UNIT 4 ASP.NET Notes
<connectionStrings>
<add name="constr" connectionString="Data
Source= .\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\Database.mdf
;
Integrated Security=True ;
Page|8
UNIT 4 ASP.NET Notes
User Instance=true"/>
</connectionStrings>
Connection String can be copy and paste from server explorer Select database property window copy
conection string.
In this web.config file connection string is enclosed in XML tag format.
using System.Configuration;
After then we declare a string variable to store connection string that getting from web.config file.
It is written as. string constr1= ConfigurationManager.
ConnectionStrings["constr"]. ConnectionString;
such connection string will enable connection with “Database.mdf” file that created using MS-SQL
Server database software.
Establishing Connection:
We need to connect our .NET application with required database file before data communication.
For this operation the connection must be opened and connection will be open by Connection Class
provided by ADO.NET. To estblising connection with different database file, we need Connection
Class.
Working with Connection Class:
Step 1: Create a connection string in web.config file.
Step 2: Include namespace: System.Data.SqlClient.
Step 3: Get Connection String in required Code Behind.
Step 4: Create Object of Connection Class and pass connection string to this object.
Step 5: Open connection.
Step 6: Perform data access operation.
Step 7: Close active connection.
Above steps can be implemented as.
Namespace: If we want to connect a Database.mdf file that created under MS-Sql Server Software
then Code Behind must included following namespace.
using System.Data.SqlClient;
Connection Class:
This namespace support following Connection Class to establishing connection.
SqlConnection
Page|9
UNIT 4 ASP.NET Notes
Before establishing connection, we need to create an connection object and passing connection string
to the constructor of Connection class like this-
Command Class:
This is one of component of ADO.NET. With the help of this componenet we can assign SQL
command and execute on database software using active connection.
SqlCommand
It is command class for MS-SQL Server Database.
Working process with Command Class:( for MS-SQL Server database) Step1: Include ADO.NET
namespace in code behind.
P a g e | 10
UNIT 4 ASP.NET Notes
Step4: Create Object of Command Class then Pass Sql Command and Active Connection to the
Constructor of command class.
Ex:
SqlCommand cmd = new SqlCommand(sql, con);
Here- sql= SQL Command in string form. con=
Active Connection.
Step5: Execute INSERT / UPDATE / DELETE Command using
ExecuteNonQuery() method of Command class.
Ex:
cmd.ExecuteNonQuery();
When all above steps are complete then required sql command will be executed on active connection
sucessfully.
You can turn off pooling for a specific connection by including the
Pooling=false key-value pair in your connection string. The SqlConnection class
also includes two methods ClearPool and ClearAllPools that let you clear its
associated pool or all pools currently managed by the provider within your
application respectively.
The following example shows a connection string with the connection pooling
option:
1. using System.Data.SqlClient;
2. namespace ConnectionPooling {
3. class Program {
4. static void Main(string[] args) {
5. string sqlConnectString = "Data Source=localhost;In
tegrated security=SSPI;Initial Catalog=AdventureWorks;";
6. SqlConnection connection = new SqlConnection();
7. // Set the connection string with pooling option
P a g e | 11
UNIT 4 ASP.NET Notes
1. <connectionStrings>
2. <clear />
3. <add name="sqlConnectionString" connectionString="Data Sou
rce=mySQLServer;Initial Catalog=myDatabase;Integrated Security=
True;Connection Timeout=15;Connection Lifetime=0;Min Pool Size=
0;Max Pool Size=100;Pooling=true;" />
4. </connectionStrings>
P a g e | 12
UNIT 4 ASP.NET Notes
The preceding image shows the client-side application interacts with the server-side
application through ADO.NET which is behaving as a mediator between the front end and
back end.
Note: A programming language does not understand syntax and structure of other
programming language but if it is required to interact from one to another programming
language, there will be one mediator which will help them to interact without any
problem.
Connection-Oriented in ADO.NET
P a g e | 13
UNIT 4 ASP.NET Notes
• Connection
• Command
• Datareader
• DataAdapter
• Dataset
Connection
Connection class used to establish the connection between the front end and back end:
Or
Command
Command class behaves as a bridge between the front end and back end. It contains the
query which has to perform from the front end and back end and also it contains an
object of Connection Class:
Student.aspx
1. <%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="Student.a
spx.cs"Inherits="Iare.Student"%>
P a g e | 14
UNIT 4 ASP.NET Notes
2. <!DOCTYPE html>
3. <html
4. xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. <styletype="text/css">
8. .auto-style1 {
9. width: 100%;
10. }
11.
12. </style>
13. </head>
14. <body style="height: 198px; width: 364px">
15. <form id="form1"runat="server">
16. <table class="auto-style1">
17. <tr>
18. <tdcolspan="2">
19. <asp:DropDownListID="DropDownList1"ru
nat="server"DataSourceID="Iare"DataTextField="SId"DataValueFiel
d="SId">
20. </asp:DropDownList>
21. <asp:SqlDataSourceID="Iare"runat="ser
ver"ConnectionString="<%$ ConnectionStrings:IareConnectionStrin
g %>"SelectCommand="SELECT [SId] FROM [Library]">
22. </asp:SqlDataSource>
23. </td>
24. </tr>
25. <tr>
26. <td>
27. <asp:LabelID="Label1"runat="server"Te
xt="Student First Name Is :">
28. </asp:Label>
29. </td>
30. <td>
31. <asp:TextBoxID="TextFName"runat="serv
er">
32. </asp:TextBox>
33. </td>
34. </tr>
35. <tr>
36. <td>
37. <asp:LabelID="Label2"runat="server"Te
xt="Student Last Name Is :">
38. </asp:Label>
39. </td>
40. <td>
41. <asp:TextBoxID="TextLName"runat="serv
er">
P a g e | 15
UNIT 4 ASP.NET Notes
42. </asp:TextBox>
43. </td>
44. </tr>
45. <tr>
46. <td>
47. <asp:LabelID="Label3"runat="server"Te
xt="Student Is Study :">
48. </asp:Label>
49. </td>
50. <td>
51. <asp:TextBoxID="TextCourse"runat="ser
ver">
52. </asp:TextBox>
53. </td>
54. </tr>
55. <tr>
56. <td>
57. <asp:LabelID="Lbldsply"runat="server"
>
58. </asp:Label>
59. </td>
60. <td>
61. <asp:ButtonID="Button1"runat="server"
OnClick="Button1_Click"Text="Save"/>
62. </td>
63. </tr>
64. </table>
65. <div></div>
66. </form>
67. </body>
68. </html>
P a g e | 16
UNIT 4 ASP.NET Notes
Student.aspx.cs
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.UI;
6. using System.Web.UI.WebControls;
7. using System.Data;
8. using System.Data.SqlClient;
9. namespace Iare {
10. public partial classStudent: System.Web.UI.Page {
11. SqlConnection con = newSqlConnection("integrated secu
rity=true;Initial Catalog=Iare;Data Source=.");
12. SqlCommand cmd;
13. protected void Page_Load(object sender, EventArgs e)
{
14.
15. }
16.
17. protected void Button1_Click(object sender, EventArgs
e) {
18. string s = "insert into Student values(@p1,@p2,@p
3,@p4)";
19. con.Open();
20. cmd = newSqlCommand(s, con);
21. cmd.CommandType = CommandType.Text;
22. cmd.Parameters.AddWithValue("@p1", TextFName.Text
);
23. cmd.Parameters.AddWithValue("@p2", TextLName.Text
);
24. cmd.Parameters.AddWithValue("@p3", TextCourse.Tex
t);
25. cmd.Parameters.AddWithValue("@p4", DropDownList1.
SelectedItem.Value);
26. cmd.ExecuteNonQuery();
27. con.Close();
28. Lbldsply.Text = "Student Details Has Saved";
29. }
30. }
31. }
P a g e | 17
UNIT 4 ASP.NET Notes
Executing commands:
ADO Data Reader:
Data Reader class in one of ADO.NET’s components. The purpose of this class is to hold the
reference of records that retived after executing SELECT command using ExecuteReader() method of
Command Class. SqlDataReader
It is a DataReader class for MS-SQL Server Database. Read() method of DataReader class will return
true value if records found otherwise false. Using index value(0,1,..) of DataReader object, we can
retieved column value of records.
Working process with DataReader Class:( for MS-SQL Server database) Step1: Include ADO.NET
namespace in code behind.
Ex: dr=cmd.ExecuteReader();
Step7: Check availability of retirieved records in to DataReader using Read() method. If found then
retrives column's value into controls using idex value.
Ex:
if(dr.Read()==true)
{
P a g e | 18
UNIT 4 ASP.NET Notes
A Data Adapter contains a set of data commands and a database connection to fill the
dataset and update a SQL Server database. Data Adapters form the bridge between a data
source and a dataset.
Data Adapters are designed depending on the specific data source. The following table
shows the Data Adapter classes with their data source.
• Fill (): The Fill method populates a dataset or a data table object with data from the
database. It retrieves rows from the data source using the SELECT statement
specified by an associated select command property.
The Fill method leaves the connection in the same state as it encountered before
populating the data.
•
Update (): The Update method commits the changes back to the database. It also
analyzes the RowState of each record in the DataSet and calls the appropriate
INSERT, UPDATE, and DELETE statements.
Example:
SqlDataAdapter da=new SqlDataAdapter("Select * from
Employee", con);
da.Fill(ds,"Emp");
bldr =new SqlCommandBuilder(da);
dataGridView1.DataSource = ds.Tables["Emp"];
P a g e | 19
UNIT 4 ASP.NET Notes
DataAdapter:
DataAdapter class of ADO.NET can be be used to execute any SQL comaand on given
connection and retrieved records can be filled into given Dataset.
SqlDataAdapter
It is a DataAdapter class for MS-SQL Server.
Fill() method of DataAdapter class that can be used to papulate dataset.
Dataset:
Dataset is a class of ADO.NET which is used to store records that retrieved from any
source like MS-SQL server, or XML files. When Dataset is papulated by records from any
source then records of Dataset can be shown on any Data bind control like GridView.
Working process with DataAdapter and Dataset Class:( for MS-SQL
Server database)
Step1: Include ADO.NET namespace in code behind.
Ex: using System.Data.SqlClient ;
Step2: Open Database Connection.
Ex:
SqlConnection con = new SqlConnection(constr1); con.Open();
Here constr1 is Connection String for required database connectivity.
Step3: Write Required SELECT SQL command in string formate.
Ex:
string sql= "SELECT * FROM Book";
Step4: Create Object of Command Class then Pass Sql Command and Active Connection
to the Constructor of command class.
Ex: SqlCommand cmd = new SqlCommand(sql, con);
Here- sql= SQL Command in string form.
con= Active Connection.
Step5: Create Object of DataAdapter class then pass object of Command Class to its
Constructur.
Ex: SqlDataAdapter da = new SqlDataAdapter (cmd);
Step6: Create Object of Dataset class.
Ex: Dataset ds = new Dataset();
P a g e | 20
UNIT 4 ASP.NET Notes
Step7: Call Fill() method of DataAdapter class and pass object of Dataset to fill retrived
records.
Ex: da.Fill(ds); Here-
Da=DataReader
ds= Dataset
When all above steps are complete then required SELECT sql command will be executed
on active connection successfully and records will be fillup into Dataset.
Properties Description
P a g e | 21
UNIT 4 ASP.NET Notes
Events Gets the list of event handlers that are attached to this
component.
Ex: GridView1.DataSource=ds;
Step9: Bind GridView control so that data can be shown on control.
P a g e | 22
UNIT 4 ASP.NET Notes
Ex: GridView1.DataBind();
When all above steps are completed then data of Dataset can be bindup to the data
bound control like Grid View.
DATASET
Methods Description
AcceptChanges
Accepts all changes made since the DataSet was loaded or this method was called.
P a g e | 23
UNIT 4 ASP.NET Notes
GetChanges Returns a copy of the DataSet with all changes made since it was
loaded or the AcceptChanges method was called.
GetChanges(DataRowState) Gets a copy of DataSet with all changes made since it was loaded
or the AcceptChanges method was called, filtered by
DataRowState.
P a g e | 24
UNIT 4 ASP.NET Notes
GetXMLSchema Returns the XSD schema for the XML representation of the data.
Load(IDataReader, Fills a DataSet with values from a data source using the supplied
LoadOption, DataTable[]) IDataReader, using an array of DataTable instances to supply the
schema and namespace information.
Load(IDataReader, Fills a DataSet with values from a data source using the supplied
LoadOption, String[]) IDataReader, using an array of strings to supply the names for the
tables within the DataSet.
Merge() Merges the data with data from another DataSet. This method
has different overloaded forms.
ReadXML() Reads an XML schema and data into the DataSet. This method
has different overloaded forms.
ReadXMLSchema(0) Reads an XML schema into the DataSet. This method has
different overloaded forms.
RejectChanges Rolls back all changes made since the last call to
AcceptChanges.
WriteXML() Writes an XML schema and data from the DataSet. This method
has different overloaded forms.
P a g e | 25
UNIT 4 ASP.NET Notes
Properties Description
PrimaryKey Gets or sets an array of columns as the primary key for the table.
The following table shows some important methods of the DataTable class:
Methods Description
P a g e | 26
UNIT 4 ASP.NET Notes
GetChanges Returns a copy of the DataTable with all changes made since the
AcceptChanges method was called.
LoadDataRow Finds and updates a specific row, or creates a new one, if not
found any.
RejectChanges Rolls back all changes made since the last call to
AcceptChanges.
Example
So far, we have used tables and databases already existing in our computer. In this
example, we will create a table, add column, rows and data into it and display the
table using a GridView object.
The source file code is as given:
P a g e | 27
UNIT 4 ASP.NET Notes
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
The code behind file is as given:
namespace createdatabase
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = CreateDataSet();
GridView1.DataSource = ds.Tables["Student"];
GridView1.DataBind();
}
}
P a g e | 28
UNIT 4 ASP.NET Notes
return dataset;
}
// adding columns
AddNewColumn(Students, "System.Int32", "StudentID");
AddNewColumn(Students, "System.String", "StudentName");
AddNewColumn(Students, "System.String", "StudentCity");
// adding rows
AddNewRow(Students, 1, "M H Kabir", "Kolkata");
AddNewRow(Students, 1, "Shreya Sharma", "Delhi");
AddNewRow(Students, 1, "Rini Mukherjee", "Hyderabad");
AddNewRow(Students, 1, "Sunil Dubey", "Bikaner");
AddNewRow(Students, 1, "Rajat Mishra", "Patna");
return Students;
}
P a g e | 29
UNIT 4 ASP.NET Notes
When the page is executed, it returns the rows of the table as shown:
QUESTIONS To PREPARE
Build a program to Display data on web form using Data bound controls.
Discuss working with transactions like insert and update command with its syntax.
Discuss working with transactions like Select and Delete command with its syntax.
P a g e | 30