0% found this document useful (0 votes)
22 views20 pages

ADO .Net Conectivity

Uploaded by

kumar.nivas7573
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views20 pages

ADO .Net Conectivity

Uploaded by

kumar.nivas7573
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

GOODWILL CHRISTIAN COLLEGE FOR WOMEN

C# AND DOT NET


FRAMEWORK
UNIT 5 ADO .NET CONNECTIVITY
KAVITHA RAJALAKSHMI D
KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

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.

WHAT TYPES OF APPLICATIONS USE ADO.NET?


ADO.NET can be used to develop any kind of .NET application. The following are some of
the .NET applications where you can use ADO.NET Data Access Technology to interact with
a data source.

 ASP.NET Web Form Applications


 Windows Applications
 ASP.NET MVC Application
 Console Applications
 ASP.NET Web API Applications
 ASP.NET Core Applications

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:

 Data Provider and


 DataSet.

WHAT ARE .NET DATA PROVIDERS?


The Database can not directly execute our C# code, it only understands SQL. So, if a .NET
application needs to retrieve data or to do some insert, update, and delete operations from or
to a database, then the .NET application needs to

 Connect to the Database


 Prepare an SQL Command
 Execute the Command
 Retrieve the results and display them in the application

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

Figure 1 ADO .NET ARCHITECTURE

Dataset provides the following components:

 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:

 Connection: This provides connectivity to the data source


 Command: This executes the database statements needed to retrieve data, modify data
or execute stored procedures.
 DataReader: This retrieves data in forward only and read-only form.
 DataAdapter: This acts as bridge between dataset and data source to load the dataset
and reconcile changes made in dataset back to the source.

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.

DIFFERENCE BETWEEN ADO AND ADO.NET

Head to Head
ADO ADO.NET
differences

In ADO, data is In ADO.NET, data is represented by a


represented by a RecordSet DataSet object, which can hold data
Data object, which can hold data from various data sources, integrate it,
Representation from one data source at a and after combining all the data it can
time. write it back to one or several data
sources.

In ADO, data is read in In ADO.NET, data is read either in a


Data Reads
sequential manner. sequential or non-sequential manner.

ADO first makes a call to It uses standardized calls such as


an OLE DB provider. It DataSetCommand object to
Disconnected supports the connected communicate with a database and with
Access access, represented by the the OLE DB provider.
Connection with a
database.

It allows us to create client- ADO.NET either created client-side or


Creating Cursors
side cursor only. server-side cursors.

ADO has the feature of This features is not used in ADO.NET.


Locking
locking.&

This feature is not used in This feature is used in ADO.NET.


XML integration
ADO.

It requires SQL Join and It uses DataRelation objects for


Relationship
UNIONs to combine data combining data from multiple tables
between Multiple
from multiple tables in a without the use of SQL Join and
Tables
single RecordSet. UNIONs.

ADO requires data to be ADO.NET does not require complex


Conversion converted to data types conversions that wasted processor time.
supported by receiving

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 3


KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

system.

In ADO data is stored in a In ADO.NET, data is stored in XML


Data Storage binary form. form. With the use of XML, it stores
data more easily.

In ADO, firewalls are In ADO.NET firewalls are supported


typically configured to because ADO.NET DataSet objects use
Firewalls prevent system-level XML for representing data.
requests, such as COM
marshaling.

In this, objects are It uses XML for communication.


Communication communicate in a binary
mode.

It uses a Connection object ADO.NET does not require data


to transfer commands to a constructs because it uses strongly
Programmability
data source with defined typed characteristics of XML.
data constructs.

ADO supports only one ADO.NET supports two models of


model of connection i.e. connection i.e. Connection-Oriented
Connection Model Connection Oriented Data Data Access Architecture and
Access Architecture Disconnected Oriented Data Access
Model. Architecture.

ADO was geared for a two- ADO.NET address a multi-tiered


Environment
tiered architecture. architecture.

It derives information In ADO.NET derives information at


Metadata automatically at runtime design time on metadata in order to
based on metadata. provide better runtime performance.

In ADO multiple In ADO.NET multiple transactions can


Multiple
transactions cannot be send be send using a single connection.
Transactions
using a single connection.

It has a less number of data It has a huge and rich collection of data
Data Types
types. types.

ADO serialized data in a ADO.NET serialized data using XML.


Serialization
proprietary protocol.

ADO is less secured. ADO.NET much secured as compared


Security
to ADO.

Based on ADO is based on ADO.NET is a Common Language


Component Object

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 4


KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

Modelling. Runtime based library.

ADO technology have less ADO.NET have more scalability with


Scalability
scalable. the use of locking mechanism.

ADO technology use more ADO.NET conserves limited resources.


Resources resources as compared to
ADO.NET.

ADO have a poor In ADO.NET performance is much


Performance
performance. better as compared to ADO.

ACCESSING DATA WITH ADO .NET

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.

Relational Databases and SQL

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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 5


KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

Tables, Records, and Columns

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.

This use of foreign keys is particularly helpful in representing one-to-many or many-to-one


relationships between tables. By separating information into tables that are linked by foreign
keys, you avoid having to repeat information in records. A single customer, for example, can
have multiple orders, but it is inefficient to place the same customer information (name,
phone number, credit limit, and so on) in every order record. The process of removing
redundant information from your records and shifting it to separate tables is called
normalization .

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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 6


KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

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.

Declarative Referential Integrity

Relational databases use Declarative Referential Integrity (DRI) to establish constraints on


the relationships among the various tables. For example, you might declare a constraint on
the Orders table that dictates that no order can have a CustomerID unless that CustomerID
represents a valid record in Customers. This helps you avoid two types of mistakes. First, you
cannot enter a record with an invalid CustomerID. Second, you cannot delete a Customer
record if that CustomerID is used in any order. The integrity of your data and their
relationships are thus protected.

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:

Select CustomerID, CompanyName from Customers where city = 'London'

This returns the following six records as output:

CustomerID CompanyName

---------- ----------------------------------------

AROUT Around the Horn

BSBEV B's Beverages

CONSH Consolidated Holdings


GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 7
KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

EASTC Eastern Connection

NORTS North/South

SEVES Seven Seas Imports

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:

select o.OrderID, productName

from [Order Details] od

join orders o on o.OrderID = od.OrderID

join products p on p.ProductID = od.ProductID

join customers c on o.CustomerID = c.CustomerID

where c.CompanyName = 'Vins et alcools Chevalier'

and orderDate >= '7/1/1996' and orderDate <= '7/31/1996'

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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 8


KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

The collection of constraints finds only three records that match:

OrderID ProductName

----------- ----------------------------------------

10248 Queso Cabrales

10248 Singaporean Hokkien Fried Mee

10248 Mozzarella di Giovanni

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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 9


KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

Figure 2 DATA PROVIDER-SPECIFIC CLASSES IMPLEMENTING 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:

SqlCommand cmd = new SqlCommand(SQL, conn);

// Call ExecuteReader to return a DataReader

SqlDataReader reader = cmd.ExecuteReader();

Once you're done with the data reader, call the Close method to close a data reader:

reader.Close();

DataReader Properties and Methods

Table 1 describes DataReader properties, and Table 2describes DataReader methods.


TABLE 1 THE DATAREADER PROPERTIES

PROPERTY DESCRIPTION

Depth Indicates the depth of nesting for row

FieldCount Returns number of columns in a row

IsClosed Indicates whether a data reader is closed

Item Gets the value of a column in native format

RecordsAffected Number of row affected after a transaction

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 10


KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

TABLE 2 THE DATAREADER METHODS

METHOD DESCRIPTION

Close Closes a DataRaeder object.

Read Reads next record in the data reader.

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.

Reading with the DataReader

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.

Listing 1. DataReader reads data from a SQL server database

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

// create a connection object


SqlConnection conn = new SqlConnection(ConnectionString);
// Create a command object
SqlCommand cmd = new SqlCommand(SQL, conn);
conn.Open();
// Call ExecuteReader to return a DataReader
SqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine("customer ID, Contact Name, " + "Contact Title, Address ");
Console.WriteLine("=============================");
while (reader.Read())
{
Console.Write(reader["CustomerID"].ToString() + ", ");
Console.Write(reader["ContactName"].ToString() + ", ");
Console.Write(reader["ContactTitle"].ToString() + ", ");
Console.WriteLine(reader["Address"].ToString() + ", ");
}

//Release resources
reader.Close();
conn.Close();
}
}
}

FIGURE 3. OUTPUT OF THE CUSTOMERS TABLE FROM THE DATAREADER

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:

string str = reader["CustomerID"].ToString();

Could be rewritten as this:

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 12


KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

string str = reader.GetString(0);

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 Class Signature

public class DataAdapter : System.ComponentModel.Component, System.Data.IDataAdapter

DataAdapter Constructors

Constructors Description

DataAdapter() It is used to initialize a new instance of a DataAdapter class.

It is used to initializes a new instance of a DataAdapter class


DataAdapter(DataAdapter)
from an existing object of the same type.

Methods

Method Description

CloneInternals() It is used to create a copy of this instance of


DataAdapter.

Dispose(Boolean) It is used to release the unmanaged


resources used by the DataAdapter.

Fill(DataSet) It is used to add rows in the DataSet to


match those in the data source.

FillSchema(DataSet, SchemaType, String, It is used to add a DataTable to the


IDataReader) specified DataSet.

GetFillParameters() It is used to get the parameters set by the


user when executing an SQL SELECT
statement.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 13


KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

ResetFillLoadOption() It is used to reset FillLoadOption to its


default state.

ShouldSerializeAcceptChangesDuringFill() It determines whether the


AcceptChangesDuringFill property should
be persisted or not.

ShouldSerializeFillLoadOption() It determines whether the FillLoadOption


property should be persisted or not.

ShouldSerializeTableMappings() It determines whether one or more


DataTableMapping objects exist or not.

Update(DataSet) It is used to call the respective INSERT,


UPDATE, or DELETE statements.

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:

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 15


KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

ADO.NET Web Form

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.

This web form contains the following source code.

// WebFormAdoNet.aspx

<%@ Page Language="C#" AutoEventWireup="true"


CodeBehind="WebFormAdoNet.aspx.cs"
Inherits="ado.netWebFormExample.WebFormAdoNet" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
width: 100px;
}
.auto-style3 {
width: 95px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="auto-style1">
<tr>
<td class="auto-style2">
<asp:Label runat="server" Text="User Name"
ID="usernamelabelId"></asp:Label></td>
<td>
<asp:TextBox ID="UsernameId" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td class="auto-style2">
<asp:Label runat="server" Text="Email ID"></asp:Label></td>
<td>
<asp:TextBox ID="EmailId" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td class="auto-style2">
<asp:Label runat="server" Text="Contact"></asp:Label></td>
<td>
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 16
KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

<asp:TextBox ID="ContactId" runat="server"></asp:TextBox></td>


</tr>
<tr>
<td class="auto-style2"></td>
<td>
<asp:Button ID="ButtonId" runat="server" Text="Submit"
OnClick="ButtonId_Click" /></td>
</tr>
</table>
</div>
<div>
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
<table class="auto-style1">
<tr>
<td class="auto-style3">
<asp:Label ID="Label2" runat="server"></asp:Label></td>
<td>
<asp:Label ID="Label5" runat="server"></asp:Label></td>
</tr>
<tr>
<td class="auto-style3">
<asp:Label ID="Label3" runat="server"></asp:Label></td>
<td>
<asp:Label ID="Label6" runat="server"></asp:Label></td>
</tr>
<tr>
<td class="auto-style3">
<asp:Label ID="Label4" runat="server"></asp:Label></td>
<td>
<asp:Label ID="Label7" runat="server"></asp:Label></td>
</tr>
</table>
</body>
</html>

// 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

It produces the following output to the browser.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 18


KAVITHA RAJALAKSHMI D ADO .NET CONNECTIVITY

Fill the form and submit data.

After submitting, it store and retrieve the data from the SQL Server database.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 19

You might also like