ADO .Net Conectivity
ADO .Net Conectivity
WHAT IS ADO.NET?
ADO stands for Microsoft ActiveX Data Objects. ADO.NET is one of Microsoft’s Data
Access Technologies using which we can communicate with different data sources. It is a
part of the .NET Framework which is used to establish a connection between the .NET
Application and different data sources. The Data Sources can be SQL Server, Oracle,
MySQL, XML, etc. ADO.NET consists of a set of predefined classes that can be used to
connect, retrieve, insert, update and delete data (i.e. performing CRUD operation) from data
sources. ADO.NET mainly uses System.Data.dll and System.Xml.dll.
COMPONENTS OF ADO.NET
Components are designed for data manipulation and faster data access. Connection,
Command, DataReader, DataAdapter, DataSet, and DataView are the components of
ADO.NET that are used to perform database operations. ADO.NET has two main
components that are used for accessing and manipulating data. They are as follows:
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.
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 1
KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY
a complete set of data including related tables, constraints and their relationships
functionality-like access to remote data from XML Web service
manipulation of data dynamically
data processing in a connectionless manner
provision for hierarchical XML view of relational data
usage of tools like XSLT and XPath Query to operate on the data
The .NET framework data provider includes the following components for data manipulation:
Using ADO.NET requires writing SQL queries by hand, either as stored procedures
(“sprocs”) that live in the database, or as “in-line” SQL strings in the code. It offers a much
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 2
KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY
lower level of control compared to an ORM based solution. In scenarios where our
application requires fine grained control of database access, it may be the right choice.
The drawback to using ADO.NET directly in lack of an ORM is that we are on the hook to
write all the plumbing. EF gives us a lot for free in this regards. One drawback of Entity
Framework, though, is that because it is such a high level abstraction, it can be difficult for
developers to wrap their head around what it’s doing and debug problems when they arise.
Head to Head
ADO ADO.NET
differences
system.
It has a less number of data It has a huge and rich collection of data
Data Types
types. types.
Many real-world applications need to interact with a database. The .NET Framework
provides a rich set of objects to manage database interaction; these classes are collectively
referred to as ADO.NET.
ADO.NET looks very similar to ADO, its predecessor. The key difference is that ADO.NET
is a disconnected data architecture. In a disconnected architecture, data is retrieved from a
database and cached on your local machine. You manipulate the data on your local computer
and connect to the database only when you wish to alter records or acquire new data.
There are significant advantages to disconnecting your data architecture from your database.
The biggest advantage is that you avoid many of the problems associated with connected data
objects which do not scale very well. Database connections are resource-intensive, and it is
difficult to have thousands (or hundreds of thousands) of simultaneous continuous
connections. A disconnected architecture is resource-frugal.
ADO.NET connects to the database to retrieve data, and connects again to update data when
you’ve made changes. Most applications spend most of their time simply reading through
data and displaying it; ADO.NET provides a disconnected subset of the data for your use
while reading and displaying.
Disconnected data objects work in a mode similar to that of the Web. All web sessions are
disconnected, and state is not preserved between web page requests. A disconnected data
architecture makes for a cleaner marriage with the Web.
Although one can certainly write an entire book on relational databases, and another on SQL,
the essentials of these technologies are not hard to understand. A database is a repository of
data. A relational database organizes your data into tables. Consider the Northwind database
provided with Microsoft SQL Server 7, SQL Server 2000, and all versions of Microsoft
Access.
The Northwind database describes a fictional company buying and selling food products. The
data for Northwind is divided into 13 tables, including Customers, Employees, Orders, Order
Details, Products, and so forth.
Every table in a relational database is organized into rows, where each row represents a single
record. The rows are organized into columns. All the rows in a table have the same column
structure. For example, the Orders table has these columns: OrderID, CustomerID,
EmployeeID, OrderDate, etc.
For any given order, you need to know the customer’s name, address, contact name, and so
forth. You could store that information with each order, but that would be very inefficient.
Instead, we use a second table called Customers, in which each row represents a single
customer. In the Customers table is a column for the CustomerID. Each customer has a
unique ID, and that field is marked as the primary key for that table. A primary key is the
column or combination of columns that uniquely identifies a record in a given table.
The Orders table uses the CustomerID as a foreign key. A foreign key is a column (or
combination of columns) that is a primary (or otherwise unique) key from a different table.
The Orders table uses the CustomerID, which is the primary key used in the Customers table,
to identify which customer has placed the order. To determine the address for the order, you
can use the CustomerID to look up the customer record in the Customers table.
Normalization
Normalization not only makes your use of the database more efficient, but also it reduces the
likelihood of data corruption. If you kept the customer’s name both in the Customers table
and also in the Orders table, you would run the risk that a change in one table might not be
reflected in the other. Thus, if you changed the customer’s address in the Customers table,
that change might not be reflected in every row in the Orders table (and a lot of work would
be necessary to make sure that it was reflected). By keeping only the CustomerID in Orders,
you are free to change the address in Customers, and the change is automatically reflected for
each order.
Just as C# programmers want the compiler to catch bugs at compile time rather than at
runtime, database programmers want the database to help them avoid data corruption. The
compiler helps avoid bugs in C# by enforcing the rules of the language; for example, you
can’t use a variable you’ve not defined. SQL Server and other modern relational databases
avoid bugs by enforcing constraints that you request. For example, the Customers database
marks the CustomerID as a primary key. This creates a primary key constraint in the
database, which ensures that each CustomerID is unique. If you were to enter a customer
named Liberty Associates, Inc. with the CustomerID of LIBE, and then tried to add Liberty
Mutual Funds with a CustomerID of LIBE, the database would reject the second record
because of the primary key constraint.
SQL
The most popular language for querying and manipulating databases is SQL, usually
pronounced “sequel.” SQL is a declarative language, as opposed to a procedural language,
and it can take a while to get used to working with a declarative language when you are used
to languages such as C#.
The heart of SQL is the query. A query is a statement that returns a set of records from the
database.
For example, you might like to see all the CompanyNames and CustomerIDs of every record
in the Customers table where the customer’s address is in London. To do so you would write:
CustomerID CompanyName
---------- ----------------------------------------
NORTS North/South
SQL is capable of much more powerful queries. For example, suppose the Northwinds
manager would like to know what products were purchased in July of 1996 by the customer
“Vins et alcools Chevalier.” This turns out to be somewhat complicated. The Order Details
table knows the ProductID for all the products in any given order. The Orders table knows
which CustomerIDs are associated with an order. The Customers table knows the
CustomerID for a customer, and the Products table knows the Product name for the
ProductID. How do you tie all this together? Here’s the query:
This query asks the database to get the OrderID and the product name from the relevant
tables: first look at Order Details (which we’ve called od for short), then join that with the
Orders table for every record where the OrderID in the Order Details table is the same as the
OrderID in the Orders table.
When you join two tables you can say either “Get every record that exists in either table”
(this is called an outer join), or you can say, as I’ve done here, “Get only those records that
exist in both tables” (called an inner join). That is, an inner join says: get only the records in
Orders that match the records in Order Details by having the same value in the OrderID field
(on o.Orderid = od.Orderid).
The SQL statement goes on to ask the database to create an inner join with Products, getting
every row where the ProductID in the Products table is the same as the ProductID in the
Order Details table.
You then create an inner join with customers for those rows where the CustomerID is the
same in both the Orders table and the Customer table.
Finally, you tell the database to constrain the results to only those rows where the
CompanyName is the one you want, and the dates are in July.
OrderID ProductName
----------- ----------------------------------------
This output shows that there was only one order (10248) where the customer had the right ID
and where the date of the order was July 1996. That order produced three records in the Order
Details table, and using the product IDs in these three records, we got the product names from
the Products table.
You can use SQL not only for searching for and retrieving data, but also for creating,
updating, and deleting tables and generally managing and manipulating both the content and
the structure of the database.
DATAREADER IN ADO.NET
A data reader provides an easy way for the programmer to read data from a database as if it
were coming from a stream. The DataReader is the solution for forward streaming data
through ADO.NET. The data reader is also called a firehose cursor or forward read-only
cursor because it moves forward through the data. The data reader not only allows you to
move forward through each record of database, but it also enables you to parse the data from
each column. The DataReader class represents a data reader in ADO.NET.
Similar to other ADO.NET objects, each data provider has a data reader class for example;
OleDbDataReader is the data reader class for OleDb data providers. Similarly,
SqlDataReader and ODBC DataReader are data reader classes for SQL and ODBC data
providers, respectively.
The IDataReader interface defines the functionally of a data reader and works as the base
class for all data provider-specific data reader classes such as OleDataReader.
SqlDataReader, and OdbcDataReader. Figure 2 shows some of the classes that implement
IDbDataReader.
Initializing DataReader
As you've seen in the previous examples, you call the ExecuteReader method of the
Command object, which returns an instance of the DataReader. For example, use the
following line of code:
Once you're done with the data reader, call the Close method to close a data reader:
reader.Close();
PROPERTY DESCRIPTION
METHOD DESCRIPTION
NextResult Advances the data reader to the next result during batch transactions.
There are dozens of Getxxx methods. These methods read a specific data type
Getxxx value from a column. For example. GetChar will return a column value as a
character and GetString as a string.
Once the OleDbDataReader is initialize, you can utilize its various methods to read your data
records. Foremost, you can use the Read method, which, when called repeatedly, continues to
read each row of data into the DataReader object. The DataReader also provides a simple
indexer that enables you to pull each column of data from the row. Below is an example of
using the DataReader in the Northwind database for the Customers table and displaying data
on the console.
As you can see from listing 1, I've used similar steps as I've been using in previous
examples. I created a connection object, created a command object, called the ExecuteReader
method, called the DataReader's Read method until the end of the data, and then displayed
the data. At the end, I released the data reader and connection objects.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
namespace CommandTypeEnumeration
{
class Program
{
static void Main(string[] args)
{
// Create a connection string
string ConnectionString = "Integrated Security = SSPI; " +
"Initial Catalog= Northwind; " + " Data source = localhost; ";
string SQL = "SELECT * FROM Customers";
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 11
KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY
//Release resources
reader.Close();
conn.Close();
}
}
}
Other methods in the Reader allow you to get the value of a column as a specific type. For
instance, this line from the previous example:
With the GetString method of the CustomerID, you don't need to do any conversion, but you
do have known the zero-based column number of the CustomerID (Which, in this case, is
zero).
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
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataSetDemo.aspx.cs"
Inherits="DataSetExample.DataSetDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" CellPadding="3" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellSpacing="2">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 14
KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY
</form>
</body>
</html>
CodeBehind
using System;
using System.Data.SqlClient;
using System.Data;
namespace DataSetExample
{
public partial class DataSetDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("data source=.; database=student;
integrated security=SSPI"))
{
SqlDataAdapter sde = new SqlDataAdapter("Select * from student", con);
DataSet ds = new DataSet();
sde.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
}
Output:
We can create a web form that has ADO.NET connectivity. A simple web form that has form
controls can be submitted to the server. ADO.NET allows us to store the submitted values to
store into SQL Server database.
Here, we are creating a web form application that connects to the SQL Server database.
// WebFormAdoNet.aspx
// WebFormAdoNet.aspx.cs
using System;
using System.Data.SqlClient;
namespace ado.netWebFormExample
{
public partial class WebFormAdoNet : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonId_Click(object sender, EventArgs e)
{
SqlConnection con = null;
try
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 17
KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY
{
// Creating Connection
con = new SqlConnection("data source=.; database=student; integrated
security=SSPI");
// Writing insert query
string query = "insert into student(name,email,contact)values('"+UsernameId.Text+
"',
'" + EmailId.Text + "','" + ContactId.Text + "')";
SqlCommand sc = new SqlCommand(query,con);
// Opening connection
con.Open();
// Executing query
int status = sc.ExecuteNonQuery();
Label1.Text = "Your record has been saved with the following details!";
// ----------------------- Retrieving Data ------------------ //
SqlCommand cm = new SqlCommand("select top 1 * from student", con);
// Executing the SQL query
SqlDataReader sdr = cm.ExecuteReader();
sdr.Read();
Label2.Text = "User Name"; Label5.Text = sdr["name"].ToString();
Label3.Text = "Email ID"; Label6.Text = sdr["email"].ToString();
Label4.Text = "Contact"; Label7.Text = sdr["contact"].ToString();
}
catch (Exception ex)
{
Console.WriteLine("OOPs, something went wrong." + ex);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}
Output
After submitting, it store and retrieve the data from the SQL Server database.