Unit Ii
Unit Ii
Unit Ii
Net Technologies
LECTURE NOTES
Unit 2-ADO.Net
Intro to ADO.Net,
Data Binding,
ADO.NET
INTRODUCTION
It is a module of .Net Framework which is used to establish connection between application
and data sources. Data sources can be such as SQL Server and XML. ADO.NET consists of
classes that can be used to connect, retrieve, insert and delete data.
All the ADO.NET classes are located into System.Data.dll and integrated with XML classes
located into System.Xml.dll.
ADO.NET has two main components that are used for accessing and manipulating data are
the .NET Framework data provider and the DataSet.
THE DATASET
It is used to access data independently from any data resource. DataSet contains a collection
of one or more DataTable objects of data. The following diagram shows the relationship
between .NET Framework data provider and DataSet.
Classic ADO used OLE DB data provider to access data and is COM based, while ADO.net uses
XML as the format for transmitting data to and from your database and applications. It is
compatible with any component on any platform that understands XML.
ADO works with connected data architecture. That means, when you access the data from
data source, such as viewing or updating data, ADO recordset is keeping connection with the
data source. This is barring, of course, you have to develop special routines to pull all your
data into temporary tables.
ADO.NET uses data in a disconnected manner. When you access data, ADO.NET makes a copy
of the data using XML. ADO.NET only holds the connection open long enough to either pull
down the data or to make any requested updates and immediatly close the connection after
operation. This makes ADO.NET efficient to use in networking environment.
Classic ADO has one main object that is used to reference data, called the Recordset object,
it acts like a single table or query result. If an ADO recordset is to contain data from multiple
In ADO.NET, you have various objects that allow you to access data in various ways. ADO.net
Dataset can contain multiple tables from various data sources. The tables within a dataset
are called data tables. The DataSet object will actually allow you to store the relational model
of your database. If a dataset contains data from multiple database tables, it will typically
contain multiple DataTable objects. That is, each DataTable object typically corresponds to a
single database table or view.
ADO allows you to create client side cursors only, whereas ADO.NET gives you the choice of
either using client side or server side cursors. In ADO.NET, classes actually handle the work
of cursors. This allows a choice for programmers. In networking development environment ,
this choice is crucial in creating efficient applications.
In ADO.Net we can send multiple transactions using a single connection instance, whereas in
ADO, we cannot send multiple transactions using a single connection instance.
In ADO, it is sometime create problems because firewall prohibits many types of request,
while in ADO.net there is no such problem because XML is completely firewall-proof.
ADO ADO.NET
The .NET Framework provides the following data providers that we can use in our application.
.NET Framework Data Provider It provides data access for Microsoft SQL Server. It
for SQL Server requires the System.Data.SqlClient namespace.
.NET Framework Data Provider It is used to connect with OLE DB. It requires
for OLE DB the System.Data.OleDb namespace.
.NET Framework Data Provider It is used to connect to data sources by using ODBC. It
for ODBC requires the System.Data.Odbc namespace.
.NET Framework Data Provider It is used for Oracle data sources. It uses
for Oracle the System.Data.OracleClientnamespace.
EntityClient Provider It provides data access for Entity Data Model applications.
It requires the System.Data.EntityClient namespace.
.NET Framework Data Provider It provides data access for Microsoft SQL Server Compact
for SQL Server Compact 4.0. 4.0. It requires
the System.Data.SqlServerCe namespace.
Object Description
DataReader It is used to read data from data source. The DbDataReader is a base
class for all DataReader objects.
DataAdapter It populates a DataSet and resolves updates with the data source. The
base class for all DataAdapter objects is the DbDataAdapter class.
The .NET Framework Data Provider for SQL Server classes is located in
the System.Data.SqlClient namespace. We can include this namespace in our C#
application by using the following syntax.
1. using System.Data.SqlClient;
Class Description
SqlDataReader It is used to read rows from a SQL Server database. This class
cannot be inherited.
1. using System.Data;
2. using System.Data.OracleClient;
.NET Framework Data It is good for middle and single-tier applications that
Provider for ODBC use ODBC data sources.
.NET Framework Data It is good for middle and single-tier applications that
Provider for Oracle use Oracle data sources.
It will prompt for database connection. Provide the server name and authentication.
2. Creating Database
Click on the New Database then it will ask for the database name. Here, we have
created a Student database.
Click on the Ok button then it will create a database that we can see in the left window
of the below screenshot.
After creating database, now, let's create a table by using the following C# code. In
this source code, we are using created student database to connect.
In visual studio 2017, we created a .NET console application project that contains the
following C# code.
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().CreateTable();
10. }
Execute this code using Ctrl+F5. After executing, it displays a message to the console
as below.
We can see the created table in Microsoft SQL Server Management Studio also. It
shows the created table as shown below.
See, we have a table here. Initially, this table is empty so we need to insert data into
it.
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().CreateTable();
10. }
11. public void CreateTable()
12. {
13. SqlConnection con = null;
14. try
15. {
16. // Creating Connection
17. con = new SqlConnection("data source=.; database=student; integrated
security=SSPI");
18. // writing sql query
19. SqlCommand cm = new SqlCommand("insert into student
20. (id, name, email, join_date)values('101','Ronald Trump','ronald@example
.com','1/12/2017')", con);
21. // Opening Connection
22. con.Open();
23. // Executing the SQL query
24. cm.ExecuteNonQuery();
25. // Displaying a message
26. Console.WriteLine("Record Inserted Successfully");
27. }
28. catch (Exception e)
29. {
30. Console.WriteLine("OOPs, something went wrong."+e);
31. }
32. // Closing the connection
33. finally
34. {
35. con.Close();
36. }
37. }
38. }
39. }
Execute this code by using Ctrl+F5 and it will display the following output.
5. Retrieve Record
Here, we will retrieve the inserted data. Look at the following C# code.
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().CreateTable();
10. }
11. public void CreateTable()
12. {
13. SqlConnection con = null;
14. try
15. {
16. // Creating Connection
17. con = new SqlConnection("data source=.; database=student; integrated
security=SSPI");
18. // writing sql query
19. SqlCommand cm = new SqlCommand("Select * from student", con);
20. // Opening Connection
21. con.Open();
22. // Executing the SQL query
23. SqlDataReader sdr = cm.ExecuteReader();
24. // Iterating Data
25. while (sdr.Read())
26. {
Execute this code by Ctrl+F5 and it will produce the following result. This displays two
records, one we inserted manually.
Output:
6. Deleting Record
This time student table contains two records. The following C# code delete one row from the
table.
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
Output:
Connection does not close explicitly even it goes out of scope. Therefore, you must explicitly
close the connection by calling Close() method.
SQLCONNECTION SIGNATURE
SQLCONNECTION CONSTRUCTORS
Constructors Description
SqlConnection Methods
Method Description
ChangePassword(String, String) It changes the SQL Server password for the user indicated in the
GetSchema() It returns schema information for the data source of this SqlConn
SQLCONNECTION EXAMPLE
Now, let's create an example that establishes a connection to the SQL Server. We have
created a Student database and will use it to connect. Look at the following C# code.
Using block is used to close the connection automatically. We don't need to call close ()
method explicitly, using block do this for ours implicitly when the code exits the block.
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().Connecting();
10. }
11. public void Connecting()
12. {
13. using (
14. // Creating Connection
15. SqlConnection con = new SqlConnection("data source=.; database=student;
integrated security=SSPI")
16. )
17. {
18. con.Open();
19. Console.WriteLine("Connection Established Successfully");
20. }
21. }
22. }
23. }
Output:
If we don't use using block to create connection, we have to close connection explicitly. In
the following example, we are using try-block instead of using block.
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().Connecting();
10. }
11. public void Connecting()
12. {
13. SqlConnection con = null;
14. try
15. {
16. // Creating Connection
Output:
SQLCOMMAND SIGNATURE
CONSTRUCTORS
This class provides the following constructors.
Constructor Description
METHODS
Method Description
Clone() It creates a new SqlCommand object that is a copy of the current instan
ExecuteReader() It is used to send the CommandText to the Connection and builds a SqlD
ExecuteScalar() It executes the query and returns the first column of the first row in the
columns or rows are ignored.
Prepare() It is used to create a prepared version of the command by using the inst
EXAMPLE
In this example, we are creating a SqlCommand instance and executing a SQL statement.
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().CreateTable();
10. }
11. public void CreateTable()
12. {
13. SqlConnection con = null;
14. try
15. {
16. // Creating Connection
17. con = new SqlConnection("data source=.; database=student; integrated securit
y=SSPI");
18. // writing sql query
19. SqlCommand cm = new SqlCommand("select * from student", con);
20. // Opening Connection
21. con.Open();
22. // Executing the SQL query
23. SqlDataReader sdr = cm.ExecuteReader();
24. while (sdr.Read())
25. {
26. Console.WriteLine(sdr["name"]+" "+ sdr["email"]);
27. }
28. }
29. catch (Exception e)
30. {
31. Console.WriteLine("OOPs, something went wrong." + e);
32. }
33. // Closing the connection
34. finally
35. {
36. con.Close();
37. }
38. }
39. }
40. }
Output:
Execute this program by combination of Ctrl+F5 and it will produce the following output.
SQLDATAREADER SIGNATURE
SQLDATAREADER PROPERTIES
Property Description
Depth It is used to get a value that indicates the depth of nesting for the
current row.
Item[String] It is used to get the value of the specified column in its native
format given the column name.
Item[Int32] It is used to get the value of the specified column in its native
format given the column ordinal.
VisibleFieldCount It is used to get the number of fields in the SqlDataReader that are
not hidden.
METHODS
Method Description
GetValue(Int32) It is used to get the value of the specified column in its native
format.
NextResult() It is used to get the next result, when reading the results of
SQL statements.
EXAMPLE
In the following program, we are using SqlDataReader to get data from the SQL Server. A C#
code is given below.
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().GetData();
10. }
11. public void GetData()
12. {
13. SqlConnection con = null;
14. try
15. {
16. // Creating Connection
17. con = new SqlConnection("data source=.; database=student; integrated securit
y=SSPI");
18. // writing sql query
19. SqlCommand cm = new SqlCommand("select * from student", con);
20. // Opening Connection
21. con.Open();
22. // Executing the SQL query
23. SqlDataReader sdr = cm.ExecuteReader();
24. while (sdr.Read())
25. {
26. Console.WriteLine(sdr["name"]+" "+ sdr["email"]);
27. }
28. }
29. catch (Exception e)
30. {
31. Console.WriteLine("OOPs, something went wrong." + e);
32. }
33. // Closing the connection
34. finally
35. {
36. con.Close();
37. }
38. }
39. }
40. }
Output:
Execute this program by combination of Ctrl+F5 and it will produce the following output.
ADO.NET 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. We can use
DataRelation object to relate these tables. The DataSet can also be used to read and write
data as XML document.
ADO.NET provides a DataSet class that can be used to create DataSet object. It contains
constructors and methods to perform data related operations.
DATASET CONSTRUCTORS
Constructor Description
DataSet Properties
Properties Description
DataSet Methods
Method Description
Copy() It is used to copy both the structure and data for this
DataSet.
EXAMPLE:
Here, in this example, we are implementing DataSet and displaying data into a gridview.
Create a web form and drag a gridview from the toolbox to the form. We can find it inside
the data category.
// DataSetDemo.aspx
2. Inherits="DataSetExample.DataSetDemo" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. </div>
12. <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#33333
3" GridLines="None">
13. <AlternatingRowStyle BackColor="White" />
14. <EditRowStyle BackColor="#2461BF" />
15. <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
16. <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
17. <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /
>
18. <RowStyle BackColor="#EFF3FB" />
19. <SelectedRowStyle BackColor="#D1DDF1" Font-
Bold="True" ForeColor="#333333" />
20. <SortedAscendingCellStyle BackColor="#F5F7FB" />
21. <SortedAscendingHeaderStyle BackColor="#6D95E1" />
22. <SortedDescendingCellStyle BackColor="#E9EBEF" />
23. <SortedDescendingHeaderStyle BackColor="#4870BE" />
24. </asp:GridView>
25. </form>
26. </body>
27. </html>
CodeBehind
// DataSetDemo.aspx.cs
1. using System;
2. using System.Data.SqlClient;
3. using System.Data;
4. namespace DataSetExample
5. {
Output:
Execute this code by the combination of Ctrl+F5. It will produce the following output.
ADO.NET DATAADAPTER
The DataAdapter works as a bridge between a DataSet and a data source to retrieve data.
DataAdapter is a class that represents a set of SQL commands and a database connection. It
can be used to fill the DataSet and update the data source.
DataAdapter Constructors
Constructors Description
Methods
Method Description
EXAMPLE
// DataSetDemo.aspx
2. Inherits="DataSetExample.DataSetDemo" %>
3. <!DOCTYPE html>
4.
5. <html xmlns="http://www.w3.org/1999/xhtml">
6. <head runat="server">
7. <title></title>
8. </head>
9. <body>
10. <form id="form1" runat="server">
11. <div>
12.
13. </div>
14. <asp:GridView ID="GridView1" runat="server" CellPadding="3" BackColor="#DEBA
84"
15. BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellSpacing="2">
16. <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
17. <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
18. <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
19. <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
20. <SelectedRowStyle BackColor="#738A9C" Font-
Bold="True" ForeColor="White" />
21. <SortedAscendingCellStyle BackColor="#FFF1D4" />
22. <SortedAscendingHeaderStyle BackColor="#B95C30" />
23. <SortedDescendingCellStyle BackColor="#F1E5CE" />
24. <SortedDescendingHeaderStyle BackColor="#93451F" />
25. </asp:GridView>
26. </form>
27. </body>
28. </html>
CodeBehind
1. using System;
2. using System.Data.SqlClient;
3. using System.Data;
4. namespace DataSetExample
5. {
6. public partial class DataSetDemo : System.Web.UI.Page
7. {
8. protected void Page_Load(object sender, EventArgs e)
9. {
10. using (SqlConnection con = new SqlConnection("data source=.; database=st
udent; integrated security=SSPI"))
11. {
12. SqlDataAdapter sde = new SqlDataAdapter("Select * from student", con);
13. DataSet ds = new DataSet();
14. sde.Fill(ds);
15. GridView1.DataSource = ds;
16. GridView1.DataBind();
17. }
18. }
19. }
20. }
Output:
ADO.NET DATATABLE
DataTable represents relational data into tabular form. ADO.NET provides a DataTable class
to create and use data table independently. It can also be used with DataSet also. Initially,
when we create DataTable, it does not have table schema. We can create table schema by
adding columns and constraints to the table. After defining table schema, we can add rows to
the table.
DATATABLE CONSTRUCTORS
The following table contains the DataTable class constructors.
Constructors Description
DATATABLE PROPERTIES
The following table contains the DataTable class properties.
Property Description
MinimumCapacity It is used to get or set the initial starting size for this table.
Rows It is used to get the collection of rows that belong to this table.
DataTable Methods
The following table contains the DataTable class methods.
Method Description
DATATABLE EXAMPLE
Here, in the following example, we are creating a data table that populates data to the
browser. This example contains the following files.
// DataTableForm.aspx
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. </div>
12. <asp:GridView ID="GridView1" runat="server">
13. </asp:GridView>
14. </form>
15. </body>
16. </html>
CodeBehind
// DataTableForm.aspx.cs
1. using System;
2. using System.Collections.Generic;
3. using System.Data;
4. using System.Linq;
5. using System.Web;
6. using System.Web.UI;
7. using System.Web.UI.WebControls;
8. namespace DataTableDemo
9. {
10. public partial class DataTableForm : System.Web.UI.Page
11. {
12. protected void Page_Load(object sender, EventArgs e)
13. {
14. DataTable table = new DataTable();
15. table.Columns.Add("ID");
16. table.Columns.Add("Name");
17. table.Columns.Add("Email");
18. table.Rows.Add("101", "Rameez","rameez@example.com");
19. table.Rows.Add("102", "Sam Nicolus", "sam@example.com");
20. table.Rows.Add("103", "Subramanium", "subramanium@example.com");
23. GridView1.DataBind();
24. }
25. }
26. }
Output:
Output: