0% found this document useful (0 votes)
37 views30 pages

ADO.NET Overview for SQL Access

The document discusses the architecture and components of ADO.NET including Connection, Command, DataReader, DataAdapter and Dataset. It also covers data providers and using the SqlDataSource control to connect to a SQL database and perform CRUD operations.

Uploaded by

shreyaspardhi01
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)
37 views30 pages

ADO.NET Overview for SQL Access

The document discusses the architecture and components of ADO.NET including Connection, Command, DataReader, DataAdapter and Dataset. It also covers data providers and using the SqlDataSource control to connect to a SQL database and perform CRUD operations.

Uploaded by

shreyaspardhi01
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

UNIT 4 ASP.

NET Notes

Architecture of [Link]:
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 [Link] is ActiveX Data [Link]. 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 [Link] are defined and arrange in “[Link]” namespace.
The architecture of [Link] is following.

From above diagram it is clear that [Link] contain following important components. 1.
Connection
2. Command
3. DataReader
4. DataAdapter
5. Dataset

1. Connection: This component of [Link] 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 [Link] 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.

Data provider for [Link]


Data provider is used to connect to the database, execute commands and retrieve
the record. It is lightweight component with better performance. It also allows us to place
the data into DataSet to use it further in our application.

A .NET Framework data provider is used for connecting to a database, executing


commands, and retrieving results. Those results are either processed directly, placed in
a DataSet in order to be exposed to the user as needed, combined with data from multiple
sources, or remoted between tiers. .NET Framework data providers are lightweight, creating
a minimal layer between the data source and code, increasing performance without
sacrificing functionality.

The .NET Framework provides the following data providers that we can use in our
application.

.NET Framework data provider Description

.NET Framework Data Provider for It provides data access for Microsoft SQL Server. It requires
SQL Server the [Link] namespace.

.NET Framework Data Provider for It is used to connect with OLE DB. It requires
OLE DB the [Link] namespace.

.NET Framework Data Provider for It is used to connect to data sources by using ODBC. It
ODBC requires the [Link] namespace.

.NET Framework Data Provider for It is used for Oracle data sources. It uses
Oracle the [Link] namespace.

EntityClient Provider It provides data access for Entity Data Model applications. It
requires the [Link] namespace.

Page|2
UNIT 4 [Link] 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 [Link] namespace.

Connecting to data sources


A data source control interacts with the data-bound controls and hides the complex
data binding processes. These are the tools that provide data to the data bound
controls and support execution of operations like insertions, deletions, sorting, and
updates.
Each data source control wraps a particular data provider-relational databases,
XML documents, or custom classes and helps in:

• Managing connection
• Selecting data
• Managing presentation aspects like paging, caching, etc.
• Manipulating data
There are many data source controls available in [Link] 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:

• Hierarchical data source controls


• Table-based data source controls
The data source controls used for hierarchical data are:
• XMLDataSource - It allows binding to XML files and strings with or without
schema information.
• SiteMapDataSource - It allows binding to a provider that supplies site map
information.
The data source controls used for tabular data are:

Data source controls Description

SqlDataSource It represents a connection to an [Link] data provider that


returns SQL data, including data sources accessible via
OLEDB and ODBC.

ObjectDataSource It allows binding to a custom .Net business object that returns


data.

LinqdataSource It allows binding to the results of a Linq-to-SQL query


(supported by [Link] 3.5 only).

Page|3
UNIT 4 [Link] Notes

AccessDataSource It represents connection to a Microsoft Access database.

The SqlDataSource Control


The SqlDataSource control represents a connection to a relational database such
as SQL Server or Oracle database, or data accessible through OLEDB or Open
Database Connectivity (ODBC). Connection to data is made through two important
properties ConnectionString and ProviderName.
The following code snippet provides the basic syntax of the control:
<asp:SqlDataSource runat="server" ID="MySqlSource"
ProviderName='<%$ ConnectionStrings:[Link] %>'
ConnectionString='<%$ ConnectionStrings:LocalNWind %>'
SelectionCommand= "SELECT * FROM EMPLOYEES" />

<asp:GridView ID="GridView1" runat="server" DataSourceID="MySqlSource" />


Configuring various data operations on the underlying data depends upon the
various properties (property groups) of the data source control.
The following table provides the related sets of properties of the SqlDataSource
control, which provides the programming interface of the control:

Property Group Description

Gets or sets the SQL statement, parameters, and type for


DeleteCommand,
deleting rows in the underlying data.
DeleteParameters,
DeleteCommandType

Gets or sets the data filtering string and parameters.


FilterExpression,
FilterParameters

Gets or sets the SQL statement, parameters, and type for


InsertCommand,
inserting rows in the underlying database.
InsertParameters,
InsertCommandType

Gets or sets the SQL statement, parameters, and type for


SelectCommand,
retrieving rows from the underlying database.
SelectParameters,
SelectCommandType

Page|4
UNIT 4 [Link] Notes

SortParameterName Gets or sets the name of an input parameter that the


command's stored procedure will use to sort data.

Gets or sets the SQL statement, parameters, and type for


UpdateCommand,
updating rows in the underlying data store.
UpdateParameters,
UpdateCommandType

The following code snippet shows a data source control enabled for data
manipulation:
<asp:SqlDataSource runat="server" ID= "MySqlSource"
ProviderName='<%$ ConnectionStrings:[Link] %>'
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>

The ObjectDataSource Control


The ObjectDataSource Control enables user-defined classes to associate the
output of their methods to data bound controls. The programming interface of this
class is almost same as the SqlDataSource control.
Following are two important aspects of binding business objects:
• The bindable class should have a default constructor, it should be stateless,
and have methods that can be mapped to select, update, insert, and delete
semantics.
• The object must update one item at a time, batch operations are not
supported.
Let us go directly to an example to work with this control. The student class is the
class to be used with an object data source. This class has three properties: a
student id, name, and city. It has a default constructor and a GetStudents method
for retrieving data.
The student class:
public class Student
{
public int StudentID { get; set; }
public string Name { get; set; }
public string City { get; set; }

public Student()

Page|5
UNIT 4 [Link] Notes

{}

public DataSet GetStudents()


{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Students");

[Link]("StudentID", typeof(System.Int32));
[Link]("StudentName", typeof([Link]));
[Link]("StudentCity", typeof([Link]));
[Link](new object[] { 1, "M. H. Kabir", "Calcutta" });
[Link](new object[] { 2, "Ayan J. Sarkar", "Calcutta" });
[Link](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 ([Link]) 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.

• Select a data method(s) for different operations on data. In this example,


there is only one method.

Page|6
UNIT 4 [Link] 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 [Link] Notes

The AccessDataSource Control


The AccessDataSource control represents a connection to an Access database. It
is based on the SqlDataSource control and provides simpler programming
interface. The following code snippet provides the basic syntax for the data source:
<asp:AccessDataSource ID="AccessDataSource1 runat="server"
DataFile="~/App_Data/[Link]" SelectCommand="SELECT * FROM
[DotNetReferences]">
</asp:AccessDataSource>
The AccessDataSource control opens the database in read-only mode. However, it
can also be used for performing insert, update, or delete operations. This is done
using the [Link] commands and parameter collection.
Updates are problematic for Access databases from within an [Link] application
because an Access database is a plain file and the default account of the
[Link] application might not have the permission to write to the database file.

Connection String and Connection Class


The first and essential part for data communication between .NET application and any database
software like Ms Sql Server is connection establishments between them.
The connection will established using driver name, data source file name and security options that
enclosed in string formats called connection string. It means right connection string is only
responsible for establishing connection with required database file.
In [Link], connection string should be written in [Link] file under root directory of web site
so that such connection string can be available to all code behind of web forms.
Let [Link] is a Ms sql server database file created using inbuilt tools of Visual studio 2005.
Then the Format of connection string is written in [Link] file as following.

<connectionStrings>
<add name="constr" connectionString="Data
Source= .\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\[Link]
;
Integrated Security=True ;

Page|8
UNIT 4 [Link] Notes

User Instance=true"/>
</connectionStrings>

Connection String can be copy and paste from server explorer Select database property window copy
conection string.
In this [Link] file connection string is enclosed in XML tag format.

Getting connection string on code behind:


Following namespace must be included in code behind of every page to get connection string.

using [Link];

After then we declare a string variable to store connection string that getting from [Link] file.
It is written as. string constr1= ConfigurationManager.
ConnectionStrings["constr"]. ConnectionString;

such connection string will enable connection with “[Link]” 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 [Link]. To estblising connection with different database file, we need Connection
Class.
Working with Connection Class:
Step 1: Create a connection string in [Link] file.
Step 2: Include namespace: [Link].
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 [Link] file that created under MS-Sql Server Software
then Code Behind must included following namespace.
using [Link];

Connection Class:
This namespace support following Connection Class to establishing connection.
SqlConnection

Page|9
UNIT 4 [Link] Notes

Before establishing connection, we need to create an connection object and passing connection string
to the constructor of Connection class like this-

SqlConnection con= new SqlConnection(constr1); here:


con = Connection object
constr1= a string variable that contain Connection String
Opening Connection: When Connection Object is created then by calling Open () method of
Connection Class, we can create an active connection.
Like-
[Link]();
When this method executes then connection will be established with required database file.
Closing Connection: When all data communication has been performed over this active connection,
then connection must be dis connected so that connection object can be further used with same
database file or different database file. Like-
[Link]();

Command Class:
This is one of component of [Link]. 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 [Link]
namespace in code behind.

Ex: using [Link] ; Step2:


Open Database Connection.
Ex:
SqlConnection con=new SqlConnection(constr1); [Link]();
Here constr1 is Connection String for required database connectivity.
Step3: Write Required SQL command like INSERT / UPDATE / DELETE in string formate.
Ex:
To add new record
string sql= "INSERT INTO Book (BookName, Price) VALUES('[Link]',
500)";
To update new record
string sql= "UPDATE Book SET BookName= 'C#.NET', Price='400' WHERE
BookID=1";
To delete any record
string sql= "DELETE FROM Book WHERE BookID=1";

P a g e | 10
UNIT 4 [Link] 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:
[Link]();
When all above steps are complete then required sql command will be executed on active connection
sucessfully.

Connection Pooling [Link]


[Link] uses a technique called connection pooling, which minimizes
the cost of repeatedly opening and closing connections. Connection pooling
reuses existing active connections with the same connection string instead of
creating new connections when a request is made to the database. It involves
the use of a connection manager that is responsible for maintaining a list, or
pool, of available connections for a given connection string. Several pools exist
if different connection strings ask for connection pooling.

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 [Link];
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 [Link] Notes

8. [Link] = sqlConnectString + "C


onnection Timeout=30;Connection Lifetime=0;Min Pool Size=0;Max
Pool Size=100;Pooling=true;";
9. //Open connection
10. [Link]();
11. //Close connection
12. [Link]();
13. }
14. }
15. }

A Connection String in the [Link] file with connection pooling option:

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>

SQL Server connection string pooling attributes


• Connection Lifetime: Length of time in seconds after creation after which
a connection is destroyed. The default is 0, indicating that the connection
will have the maximum timeout.
• Connection Reset: Specifies whether the connection is reset when
removed from the pool. The default is true.
• Enlist: Specifies whether the connection is automatically enlisted in the
current transaction context of the creation thread if that transaction
context exists. The default is true.
• Load Balance Timeout: Length of time in seconds that a connection can
remain idle in a connection pool before being removed.
• Max Pool Size: Maximum number of connections allowed in the pool. The
default is 100.
• Min Pool Size: Minimum number of connections maintained in the pool.
The default is 0.
• Pooling: When true, the connection is drawn from the appropriate pool, or
if necessary, created and added to the appropriate pool. The default is
true.

P a g e | 12
UNIT 4 [Link] Notes

Perform Connection between Back end to front end.


ADO stands for active data object, which behaves as a mediator between the client side
and server side. Client side can’t directly interact with the server side, so there
is [Link] which behaves as a mediator between front end and back end as in the
following figure:

The preceding image shows the client-side application interacts with the server-side
application through [Link] 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 [Link]

Before discussing [Link] connection orientation we will discuss what [Link]


contains.

P a g e | 13
UNIT 4 [Link] Notes

[Link] is a group of class which contains.

• Connection
• Command
• Datareader
• DataAdapter
• Dataset
Connection

Connection class used to establish the connection between the front end and back end:

1. SqlConnection con=new SqlConnection(“Integrated security=true;initial ca


talog=Student;Data source=.”);

Or

1. SqlConnection Con=new SqlConnection(“User id=sa;Password=sa123;Database=


Student;Server=.”);

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:

1. SqlCommand cmd=new SqlCommand(“Query which has to perform”,Connection Ob


ject);

• DataReader: DataReader used to read the data from the source.


• Dataset: DataSet contains the table and relation.
• DataAdapter: DataAdapter behaves as a mediator between the back end and front
end. But it does not have features to contains the data. So there is a dataset that
contains the data of the result set.
In connection-oriented architecture the Database gets connected to the front end then the
command passes the query to the server from the back end and on the server the result
which has been generated. The result which has been generated will be read by
DataReader. Here's the screenshot:

[Link]

1. <%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="Student.a
[Link]"Inherits="[Link]"%>

P a g e | 14
UNIT 4 [Link] Notes

2. <!DOCTYPE html>
3. <html
4. xmlns="[Link]
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 [Link] 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 [Link] Notes

After designing the application go to [Link] and write the following


code.

[Link]

1. using System;
2. using [Link];
3. using [Link];
4. using [Link];
5. using [Link];
6. using [Link];
7. using [Link];
8. using [Link];
9. namespace Iare {
10. public partial classStudent: [Link] {
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. [Link]();
20. cmd = newSqlCommand(s, con);
21. [Link] = [Link];
22. [Link]("@p1", [Link]
);
23. [Link]("@p2", [Link]
);
24. [Link]("@p3", [Link]
t);
25. [Link]("@p4", DropDownList1.
[Link]);
26. [Link]();
27. [Link]();
28. [Link] = "Student Details Has Saved";
29. }
30. }
31. }

Now run the application and check.

P a g e | 17
UNIT 4 [Link] Notes

Executing commands:
ADO Data Reader:
Data Reader class in one of [Link]’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 [Link]
namespace in code behind.

Ex: using [Link] ;


Step2: Open Database Connection.
Ex:
SqlConnection con = new SqlConnection(constr1); [Link]();
Here constr1 is Connection String for required database connectivity.
Step3: Write Required SELECT SQL command in string formate.
Ex:
string sql= "SELECT * FROM Book WHERE BookID=1";
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 reference of DataReader class.

Ex: SqlDataReader dr;


Step6: Execute SELECT sql Command using ExecuteReader() method of Command class and assign
reference of retrieved records to the DataReader object reference.

Ex: dr=[Link]();
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([Link]()==true)
{

[Link]=dr[0].ToString(); // First Column Value

P a g e | 18
UNIT 4 [Link] Notes

[Link]=dr[1].ToString(); // Second Column Value


[Link]=dr[2].ToString(); // Third Column Value
}
When all above steps are complete then required SELECT sql command will be executed on active
connection sucessfully and records will be shown on destination control.

Data Adapter and Dataset Class:


A Data Adapter represents a set of data commands and a database connection to fill the
dataset and update a SQL Server database.

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.

Provider-Specific Data Adapter classes Data Source


SqlDataAdapter SQL Server
OledbDataAdapter OLE DB provider
OdbcDataAdapter ODBC driver
OracleDataAdapter Oracle

A Data Adapter supports mainly the following two methods:

• 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);
[Link](ds,"Emp");
bldr =new SqlCommandBuilder(da);
[Link] = [Link]["Emp"];

P a g e | 19
UNIT 4 [Link] Notes

DataAdapter:
DataAdapter class of [Link] 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 [Link] 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 [Link] namespace in code behind.
Ex: using [Link] ;
Step2: Open Database Connection.
Ex:
SqlConnection con = new SqlConnection(constr1); [Link]();
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 [Link] Notes

Step7: Call Fill() method of DataAdapter class and pass object of Dataset to fill retrived
records.
Ex: [Link](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.

Data Bound Control and Data Grid ( GridView Control):


Any control of [Link] that can be used to show records of any data source like MS-
SQL Server called Data Bound Control. To Bind records on Data Bound control,
DataSource property and DataBind() method is used of that control.
Data Grid or GridView Control is one most papular and important Data bound control.
Using this control we can show records on table form. The Data source of GridView
control is Dataset.
Let GridView1 is one Databound control of GridView Control then to bind Records of
Dataset we have to apply DataSource property and
DataBind() method like.
[Link] = ds;
[Link]();
Here ds= Dataset with Records.
Working process with DataBound Control (
DataGrid / GridView) First add GridView Control on web page using following [Link]
code.
<asp: GridView ID= “GridView1” runat= “server” />
Now apply following steps on page load event of web page.
Step1 to Step7 are same as DataAdpter and Dataset.
Step8: Set Data source of GridView control that is Dataset.

Properties Description

CaseSensitive Indicates whether string comparisons within the data tables


are case-sensitive.

P a g e | 21
UNIT 4 [Link] Notes

Container Gets the container for the component.

DataSetName Gets or sets the name of the current data set.

DefaultViewManager Returns a view of data in the data set.

DesignMode Indicates whether the component is currently in design


mode.

EnforceConstraints Indicates whether constraint rules are followed when


attempting any update operation.

Events Gets the list of event handlers that are attached to this
component.

ExtendedProperties Gets the collection of customized user information


associated with the DataSet.

HasErrors Indicates if there are any errors.

IsInitialized Indicates whether the DataSet is initialized.

Locale Gets or sets the locale information used to compare strings


within the table.

Namespace Gets or sets the namespace of the DataSet.

Prefix Gets or sets an XML prefix that aliases the namespace of


the DataSet.

Relations Returns the collection of DataRelation objects.

Tables Returns the collection of DataTable objects.

Ex: [Link]=ds;
Step9: Bind GridView control so that data can be shown on control.

P a g e | 22
UNIT 4 [Link] Notes

Ex: [Link]();
When all above steps are completed then data of Dataset can be bindup to the data
bound control like Grid View.

DATASET

Data container objects: Data sets, Data tables, Data Relations

The Dataset Class


The dataset represents a subset of the database. It does not have a
continuous connection to the database. To update the database a reconnection is
required. The DataSet contains DataTable objects and DataRelation objects. The
DataRelation objects represent the relationship between two tables.
Following table shows some important properties of the DataSet class:
The following table shows some important methods of the DataSet class:

Methods Description

AcceptChanges
Accepts all changes made since the DataSet was loaded or this method was called.

BeginInit Begins the initialization of the DataSet. The initialization occurs at


run time.

P a g e | 23
UNIT 4 [Link] Notes

Clear Clears data.

Clone Copies the structure of the DataSet, including all DataTable


schemas, relations, and constraints. Does not copy any data.

Copy Copies both structure and data.

CreateDataReader() Returns a DataTableReader with one result set per DataTable, in


the same sequence as the tables appear in the Tables collection.

CreateDataReader(DataTable[]) Returns a DataTableReader with one result set per DataTable.

EndInit Ends the initialization of the data set.

Equals(Object) Determines whether the specified Object is equal to the current


Object.

Finalize Free resources and perform other cleanups.

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.

GetDataSetSchema Gets a copy of XmlSchemaSet for the DataSet.

GetObjectData Populates a serialization information object with the data needed


to serialize the DataSet.

GetType Gets the type of the current instance.

GetXML Returns the XML representation of the data.

P a g e | 24
UNIT 4 [Link] Notes

GetXMLSchema Returns the XSD schema for the XML representation of the data.

HasChanges() Gets a value indicating whether the DataSet has changes,


including new, deleted, or modified rows.

HasChanges(DataRowState) Gets a value indicating whether the DataSet has changes,


including new, deleted, or modified rows, filtered by
DataRowState.

IsBinarySerialized Inspects the format of the serialized representation of the


DataSet.

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 [Link] Notes

WriteXMLSchema() Writes the structure of the DataSet as an XML schema. This


method has different overloaded forms.

The Data Table Class


The DataTable class represents the tables in the database. It has the following
important properties; most of these properties are read only properties except the
PrimaryKey property:

Properties Description

ChildRelations Returns the collection of child relationship.

Columns Returns the Columns collection.

Constraints Returns the Constraints collection.

DataSet Returns the parent DataSet.

DefaultView Returns a view of the table.

ParentRelations Returns the ParentRelations collection.

PrimaryKey Gets or sets an array of columns as the primary key for the table.

Rows Returns the Rows collection.

The following table shows some important methods of the DataTable class:

Methods Description

AcceptChanges Commits all changes since the last AcceptChanges.

Clear Clears all data from the table.

P a g e | 26
UNIT 4 [Link] Notes

GetChanges Returns a copy of the DataTable with all changes made since the
AcceptChanges method was called.

GetErrors Returns an array of rows with errors.

ImportRows Copies a new row into the table.

LoadDataRow Finds and updates a specific row, or creates a new one, if not
found any.

Merge Merges the table with another DataTable.

NewRow Creates a new DataRow.

RejectChanges Rolls back all changes made since the last call to
AcceptChanges.

Reset Resets the table to its original state.

Select Returns an array of DataRow objects.

The Data Reader Object


The DataReader object is an alternative to the DataSet and DataAdapter
combination. This object provides a connection oriented access to the data records
in the database. These objects are suitable for read-only access, such as populating
a list and then breaking the connection.

DB Command and DB Connection Objects


The DB Connection object represents a connection to the data source. The
connection could be shared among different command objects.
The DB Command object represents the command or a stored procedure sent to the
database from retrieving or manipulating data.

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 [Link] Notes

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="[Link]"


Inherits="createdatabase._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"[Link]

<html xmlns="[Link] >

<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 : [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = CreateDataSet();
[Link] = [Link]["Student"];
[Link]();
}
}

private DataSet CreateDataSet()


{
//creating a DataSet object for tables
DataSet dataset = new DataSet();

// creating the student table


DataTable Students = CreateStudentTable();
[Link](Students);

P a g e | 28
UNIT 4 [Link] Notes

return dataset;
}

private DataTable CreateStudentTable()


{
DataTable Students = new DataTable("Student");

// adding columns
AddNewColumn(Students, "System.Int32", "StudentID");
AddNewColumn(Students, "[Link]", "StudentName");
AddNewColumn(Students, "[Link]", "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;
}

private void AddNewColumn(DataTable table, string columnType, string columnName)


{
DataColumn column = [Link](columnName, [Link](columnType));
}

//adding data into the table


private void AddNewRow(DataTable table, int id, string name, string city)
{
DataRow newrow = [Link]();
newrow["StudentID"] = id;
newrow["StudentName"] = name;
newrow["StudentCity"] = city;
[Link](newrow);
}
}
}

P a g e | 29
UNIT 4 [Link] Notes

When the page is executed, it returns the rows of the table as shown:

QUESTIONS To PREPARE

Explain Architecture of [Link] in detail.


Evaluate Connection String and Connection Class with example.
Describe Working process with Data Adapter and Dataset Class with example.

Explain Data Reader Class with its steps and example.


Evaluate Working process with DataAdapter and Dataset Class:( for MS-SQLServer database)
Define: DataBound Control with example.
Discuss Data [Link] with example.
Describe Working process with Command Class with syntax.

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.

Discuss data table in detail with example.

P a g e | 30

Common questions

Powered by AI

DataBound controls like GridView in ASP.NET provide a visual interface for displaying and manipulating data, typically from a DataSet or DataReader. Advantages include automatic data rendering in a tabular format, built-in features like sorting and paging, and easy integration with data source controls. Data binding is implemented by setting the control's DataSource property to an object like a DataSet filled with the required data. The DataBind() method is then invoked to link the data to the control, rendering it on the web page. This approach simplifies development and enhances data presentation within web applications .

ADO.NET's architecture supports data access in a disconnected environment by using two key components: DataSet and DataAdapter. The DataSet acts as an in-memory cache of data retrieved from the database, allowing for data operations independently from the data source. This disconnected model enables applications to update the data source without maintaining an open connection. DataAdapter serves as the bridge between the DataSet and the data source, providing functionalities like Fill() to load data into the DataSet and Update() to reflect changes back to the data source. This architecture supports scalability and robustness in data-driven applications by minimizing constant database connections .

The Fill() and Update() methods of a DataAdapter are instrumental in synchronizing a DataSet with a data source. Fill() retrieves data from the database using a SQL SELECT statement, populating the DataSet or DataTable with the data. This operation leaves the connection state unchanged after execution. The Update() method, on the other hand, synchronizes changes made to the DataSet back to the database. It examines the RowState of each DataRow and executes the appropriate INSERT, UPDATE, or DELETE command defined in the DataAdapter, updating the data source to reflect the current state of the DataSet. This two-way synchronization allows for efficient data manipulation while minimizing database connectivity .

To design a custom DataTable within a DataSet programmatically, a developer starts by creating a DataSet instance. A new DataTable object is then instantiated with the desired table name. Columns are added by calling Add() on the DataTable's Columns collection, specifying the column’s data type and name. Rows are inserted by creating DataRow objects using NewRow(), setting column values, and adding them to the DataTable's Rows collection via the Add() method. Finally, the completed DataTable is appended to the DataSet's Tables collection to be used within the application .

The connection string in ADO.NET is a key element that defines the parameters needed to establish a connection to a data source. It typically includes the data source, database information, authentication credentials, and other configuration details. This string is crucial for the SqlConnection class, which uses it to create and manage a connection to the database. The connection string is stored securely within the application's configuration file and retrieved using the ConfigurationManager class. The SqlConnection object is instantiated with this connection string and its Open() method is called to establish the active database connection necessary for performing data operations .

Using the SqlCommand class involves several steps. First, establish an open connection to the database using SqlConnection. Next, construct the SQL query in string form. Initialize a SqlCommand object with the query and the active SqlConnection. Execute the command using ExecuteReader() on the SqlCommand object to obtain a SqlDataReader. The DataReader then reads records sequentially using Read(), allowing the application to access values from the result set. This process uses a connected approach, keeping the connection open for the duration of the read operation, ideal for forward-only, read-only access to data .

The DataReader object in ADO.NET offers fast, forward-only, read-only access to data from a database. It is optimal for scenarios requiring access to large volumes of data without manipulating it, as it consumes fewer system resources and maintains an open connection to read each record sequentially. In contrast, the DataSet provides disconnected data access, representing data in memory and allowing for data manipulation while disconnected from the database. DataReader is more efficient for read-only operations, while DataSet supports complex data operations, making them suitable for different use cases depending on performance and functionality needs .

The DataRelation object is crucial in ADO.NET for defining relationships between tables in a DataSet, mimicking relational database relationship structures. This object allows DataSet to enforce data integrity and navigate related records efficiently using parent-child relationships across tables. For example, a DataRelation can link a primary key column in a parent DataTable to a foreign key column in a child DataTable. This facilitates operations like nested data views and automated cascading updates or deletes, enabling complex data manipulation and retrieval in applications while maintaining the data integrity rules of the domain model .

Implementing transaction control in an ADO.NET application involves using the SqlTransaction class. Start by opening a database connection using SqlConnection. Then, initiate a transaction by calling the BeginTransaction() method on the connection, which returns a SqlTransaction object. Pass this transaction object to each SqlCommand by setting the Command's Transaction property. Execute commands within a try-catch block: if all commands execute successfully, call Commit() on the transaction object; if an error occurs, call Rollback() to discard all changes. This ensures atomicity, guaranteeing that all operations complete successfully as a group or none at all .

DataAdapter and DataSet classes facilitate data manipulation by enabling operations in a disconnected state. The DataAdapter uses SQL commands to retrieve data from the database and then populates a DataSet, which serves as an in-memory representation of the data. This allows manipulation, such as updates or inserts, to occur within the DataSet while disconnected from the database. Once changes are complete, DataAdapter's Update() method is called to transmit changes back to the database. The DataSet holds data in DataTable objects, which mirror database tables, allowing for local data processing and validation before reconciliation with the actual database .

You might also like