0% found this document useful (0 votes)
195 views

Intro To

ADO.NET is a set of classes that provides data access functionality in .NET and allows applications to connect to data sources like databases. It uses a disconnected model where applications connect to databases only when reading or writing data rather than maintaining a constant connection. The key classes in ADO.NET are Connection, Command, DataReader, DataAdapter and DataSet. Connection and Command classes are used to execute queries and stored procedures. DataReader retrieves data rows and DataAdapter fills DataSet objects which cache disconnected data on the application side. This allows applications to work with data without being continuously connected to the database.

Uploaded by

Shahbaz Ali
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
195 views

Intro To

ADO.NET is a set of classes that provides data access functionality in .NET and allows applications to connect to data sources like databases. It uses a disconnected model where applications connect to databases only when reading or writing data rather than maintaining a constant connection. The key classes in ADO.NET are Connection, Command, DataReader, DataAdapter and DataSet. Connection and Command classes are used to execute queries and stored procedures. DataReader retrieves data rows and DataAdapter fills DataSet objects which cache disconnected data on the application side. This allows applications to work with data without being continuously connected to the database.

Uploaded by

Shahbaz Ali
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

https://www.webtrainingroom.

com/adonet

https://www.c-sharpcorner.com/UploadFile/18fc30/understanding-the-basics-of-ado-net/

Basics of ADO.NET
ADO.NET stands for ActiveX Data Object is a database access technology created by Microsoft
as part of its .NET framework that can access any kind of data source.

Or

The .NET classes that provide data-access functionality are known as ADO.NET.

Or

ADO.NET is a set of classes (a framework) to interact with data sources such as databases and
XML files. ADO is the acronym for ActiveX Data Objects. It allows us to connect to underlying
data or databases. It has classes and methods to retrieve and manipulate data. 

The following are a few of the .NET applications that use ADO.NET to connect to a database,
execute commands and retrieve data from the database.

 ASP.NET Web Applications


 Console Applications
 Windows Applications.

Various Connection Architectures:  


There are the following two types of connection architectures:

1. Connected architecture: the application remains connected with the database


throughout the processing.

2. Disconnected architecture: the application automatically connects/disconnects during


the processing. The application uses temporary data on the application side called a
DataSet.

Understanding ADO.NET and it's class library:


 

1
 

In this diagram, we can see that there are various types of applications (Web Application,
Console Application, Windows Application and so on) that use ADO.NET to connect to
databases (SQL Server, Oracle, OleDb, ODBC, XML files and so on).

Important Classes in ADO.NET


 We can also observe various classes in the preceding diagram. They are:

1. Connection Class
2. Command Class
3. DataReader Class
4. DataAdaptor Class
5. DataSet.Class

1. Connection Class:
 

2
In ADO.NET, we use these connection classes to connect to the database. These connection
classes also manage transactions and connection pooling. To learn more about connection
classes, start here: Connection in ADO.NET. 

2. Command Class
The Command class provides methods for storing and executing SQL statements and Stored
Procedures. The following are the various commands that are executed by the Command Class.

 ExecuteReader: Returns data to the client as rows. This would typically be an SQL
select statement or a Stored Procedure that contains one or more select statements. This
method returns a DataReader object that can be used to fill a DataTable object or used
directly for printing reports and so forth.
 ExecuteNonQuery: Executes a command that changes the data in the database, such as
an update, delete, or insert statement, or a Stored Procedure that contains one or more of
these statements. This method returns an integer that is the number of rows affected by
the query.
 ExecuteScalar: This method only returns a single value. This kind of query returns a
count of rows or a calculated value.
 ExecuteXMLReader: (SqlClient classes only) Obtains data from an SQL Server 2000
database using an XML stream. Returns an XML Reader object.

3. DataReader Class 
The DataReader is used to retrieve data. It is used in conjunction with the Command class to
execute an SQL Select statement and then access the returned rows. Learn more here: Data
Reader in C#.

 4. DataAdapter Class


 The DataAdapter is used to connect DataSets to databases. The DataAdapter is most useful
when using data-bound controls in Windows Forms, but it can also be used to provide an easy
way to manage the connection between your application and the underlying database tables,
views and Stored Procedures. Learn more here: Data Adapter in ADO.NET.

5. DataSet Class
 The DataSet is the heart of ADO.NET. The DataSet is essentially a collection of DataTable
objects. In turn each object contains a collection of DataColumn and DataRow objects. The
DataSet also contains a Relations collection that can be used to define relations among Data
Table Objects.

How to Connect to a Database using ADO.NET


 Now let us learn how to connect to a database using ADO.NET. To create a connection, you
must be familiar with connection strings. A connection string is required as a parameter to
SQLConnection. A ConnectionString is a string variable (not case sensitive).

3
This contains key and value pairs, like provider, server, database, userid and word as in the
following:

Server="nameof the server or IP Address of the server"

Database="name of the database"

userid="user name who has permission to work with database"

word="the word of userid"


Example

SQL Authentication

String constr="server=.;database=institute;user id=rakesh;word=abc@123";

Or:

String constr="data source=.;initial catalog=institute;uid=rakesh;pwd=abc@213";

Windows Authentication

String constr="server=.;database=institute;trusted_connection=true"

Or:

String constr="server=.;initial catalog=institute;integrated security=true"

How to retrieve and display data from a database

1. Create a SqlConnection object using a connection string.

2. Handle exceptions.

3. Open the connection.

4. Create a SQLCommand. To represent a SQLCommand like (select * from studentdetails)


and attach the existing connection to it. Specify the type of SQLCommand
(text/storedprocedure).

5. Execute the command (use executereader).

6. Get the Result (use SqlDataReader). This is a forward only/read only data object.

7. Close the connection

4
8. Process the result
9. Display the Result

The following is code for connecting to a SQL Database:

You must use the System.Data.SqlClient namespace to connect to a SQL Database. In the
preceding code we are using the SqlConnection class, SqlCommand class and SqlDataReader
class because our application is talking to SQL Server. SQL Server only understands SQL.

Code for connecting to Oracle Database: 


If you want to connect to an Oracle database, all you need to do is to change the connection class
name from SqlConnection to OracleConnection, Command class name from SqlCommand to
OracleCommand and SqlDataReader to OracleDataReader and also in the beginning use the
namespace System.Data.OralceClient.
 
This works for OleDb and ODBC also.

Second Article

https://www.c-sharpcorner.com/uploadfile/puranindia/what-is-ado-net/

This article will provide an overview of ADO.NET. In it, I’ll provide the basics of ADO.NET,
describe its advantages over current data access technologies and briefly introduce ADO.NET

5
classes and namespaces as well as show how to use them to write simple database applications
using Visual Studio .NET.

What Is ADO.NET? 
ADO.NET stands for ActiveX Data Object is a database access technology created by Microsoft
as part of its .NET framework that can access any kind of data source. It’s a set of object-
oriented classes that provides a rich set of data components to create high-performance, reliable
and scalable database applications for client- server applications as well as distributed
environments over the Internet and intranets. 

In the ADO.NET model, unlike ADO (in connected state) and previous data access technologies
applications connect to the data sources when they are reading or updating the data. After that
the connection closes. This is important because in client- server or distributed applications,
having connection resources open all the time is one of the most resource- consuming parts. You
don’t have to connect to a data source all the time; the only time you need to connect to a data
source is when you are reading and writing final changes to a data source. 

ADO .NET uses SQL queries and stored procedures to read write update and delete data from a
data source. You use SQL queries through ADO.NET Command object, which returns data in
the form of DataReader or DataSet objects. After that connection closes, you use DataSet objects
to work with the data and connect to the data source again when you need to update the data
source. 

A dataset is a collection of DataTable objects and relationships among them. It works as a


container that stores returned data from a database in cached from. You can fill a dataset with the
data retrieved from multiple tables of a database. Once you have a dataset (which is disconnected
data, stored on your local machine), you treat the dataset changes final to the actual database.
You call the Update method to make dataset changes final to the actual database. You can even
read and update a dataset from different data sources.

You access a data source and fill a dataset via data providers. The .NET framework provides
three different types of data providers: Sql, OleDb and ODBC. Microsoft is also working on
providing a data provider for Oracle database and other Database Management System (DBMS)
suppliers may produce their own data providers. You use a DataAdapter object of a data provider
and call its Fill method to fill a dataset. 

XML plays a major role in ADO.NET. The ADO.NET model utilizes XML to store the data in
cache and transfer the data among applications. Datasets use XML schemas to store and transfer
data among applications. You can even use this XML file from other applications without
interacting with the actual dataset. You can use data among all kinds of applications and

6
components because XML is an industry standard; you can transfer data via many protocols,
such as HTTP, because of XML’s text- based nature. 

Advantages of ADO .NET 


ADO.NET offers several advantages over previous Microsoft data access technologies, including
ADO. The following section will outline these advantages. 

Single Object- Oriented API:

The ADO.NET provides a single object-oriented set of classes. There are different data providers
to work with different data sources, but the programming model for all these data providers to
work in the same way. So if you know how to work with one data provider, you can easily work
with others. It’s just a matter of changing class names and connection strings. The ADO.NET
classes are easy to use and to understand because of their object- oriented nature. 

You can use more than one data provider to access a single data source. For example, you can
use ODBC or OleDb data providers to access Microsoft access databases. 

Managed Code: 

The ADO .NET classes are managed classes. They take all the advantages of .NET CLR, such as
language independency and automatic resource management. All .NET languages access the
same API. So if you know how to use these classes in C#, you’ll have no problem using them in
VB.NET. Another big advantage is you don’t have to worry about memory allocation and
freeing it. The CLR will take care of it for you. 

Deployment: 

In real life, writing database application using ODBC, DAO, and other previous technologies and
deploying on client machines was a big problem was somewhat taken care in ADO except that
three are different versions of MDAC. Now you don’t have to worry about that. Installing
distributable .NET components will take care of it. 

XML Support: 

Today, XML is an industry standard and the most widely used method of sharing data among
applications over the Internet. As discussed earlier in ADO .NET data is cached and transferred
in XML format. All components and applications can share this data and you can transfer data
via different protocols such as HTTP.

 Visual Data Components: 

Visual Studio .NET offers ADO .NET components and data– bound controls to work in visual
form. That means you can use these components as you use any windows controls. You drag and
drop these components on windows and web forms set their properties and write events. It helps

7
programmers to write less code and develop applications in no time. VS .NET also offers the
data form wizard, which you can use to write full-fledged database applications without writing a
single line of code. Using these components, you can directly bind these components with data-
bound controls by setting these control’s properties at design-time. 

Performance and Scalability: 

Performance and scalability are two major factors when developing web-based applications and
services. Transferring data one source to another is a costly affair over the Internet because of
connection bandwidth limitations and rapidly increasing traffic. Using disconnected cached data
in XML takes care of both of these problems. 

Connections and Disconnected data: 

With ADO .NET you use as few connections as possible and have more disconnected data. Both
the ADO and ADO .NET models support disconnected data but ADO’S record set object wasn’t
actually designed to work with disconnected data. So there are performance problems with that.
However, ADO.NET’s dataset is specifically designed to work with disconnected data and you
can treat a dataset as a local copy of a database. In ADO.NET, you store data in a dataset and
close the make final changes to the data source. The ADO model is not flexible enough for XML
users; ADO uses OLE-DB persistence provider to support XML. 

DataReader versus DataSet: 

The ADO.NET DataReader is used to retrieve read-only (cannot update data back to a
datasource) and forward-only (cannot read backward/random) data from a database. You create a
DataReader by calling Command.ExecuteReader after creating an instance of the Command
object. Learn more about DataReader vs DataSet.

LINQ to DataSet 

LINQ to DataSet API provides queries capabilities on a cached DataSet object using LINQ
queries. The LINQ queries are written in C#. Learn more here: LINQ to DataSet

LINQ to SQL 

LINQ to SQL API provides queries against relational databases without using a middle layer
database library. Learn more here: LINQ to SQL in C#

ADO.NET Entity Framework

The ADO.NET Entity Framework is designed to enable developers to create data access
applications by programming against a conceptual application model instead of programming
directly against a relational storage schema. The goal is to decrease the amount of code and

8
maintenance required for data-oriented applications. For more information, see ADO.NET Entity
Framework. ADO.NET Entity Framework and ADO.NET

ADO.NET Components:
The ADO.NET is designed to work with multiple kinds of data sources in same fashion. You can
categorize ADO.NET components in three categories: disconnected, common or shared and
the .NET data providers. The disconnected components build the basic ADO.NET architecture.
You can use these components (or classes) with or without data providers. For example, you can
use a DataTable object with or without providers and shared or common components are the
base classes for data providers. Shared or common components are the base classes for data
providers and shared by all data providers. The data provider components are specifically
designed to work with different kinds of data sources. For example, ODBC data providers work
with ODBC data sources and OleDb data providers work with OLE-DB data sources. The
following figure represents the ADO.NET components model and how they work together:

9
A data provider is a set of components, such as Connection, Command, DataAdapter and
DataReader. The Connection is the first component that talks to a data source. The Connection
object establishes a connection to a data source and works as a connection reference in
Command and DataAdapter objects. A Command object executes a SQL query and stored
procedures to read, add, update, and delete data of a data source via a DataAdapter. A
DataAdapter is a bridge between a dataset and the connection. It uses Command Object to
execute SQL queries and stored procedures. 

All data providers share the ADO.NET common components. These components represent the
data. Some of the common components are DataSet, DataView, and DataViewManager. The
DataSet uses XML to store and transfer data between the applications and the data provider. A
DataSet is a set of DataTable objects. A DataTable represents a database table. The DataView
and DataViewManager objects provide single or multiple views of a dataset. You can attach a
DataView or a DataViewManager directly to data–bound controls such as a DataGrid or
DataList. Other common components are DataTable, DataRow, DataColumn and so on. Now,
I’ll break down the ADO.NET model to show how it works. 

Connection Object:  

The Connection object is the first component of ADO.NET that you should be looking at. A
connection sets a link between a data source and ADO.NET. A Connection object sits between a
data source and a DataAdapter (via Command). You need to define a data provider and a data
source when you create a connection. With these two, you can also specify the user ID and
password depending on the type of data source. 

Connection can also be connected to a Command object to execute SQL queries, which can be
used to retrieve, add, update and delete data to a data source. 

The Connection object also plays a useful role in creating a transaction. Transactions are stored
in transactions objects, and transaction classes have all those nice features for dealing with
transactions such as commit and rollback. Learn more about SqlConnection here: SqlConnection
In ADO.NET 

Command object: 

The Command object can execute SQL queries and stored procedures. You can execute SQL
queries to return data in a DataSet or a DataReader object. To retrieve add, update and delete
data you use SELECT, INSERT, UPDATE, and DELETE SQL queries. A DataAdapter
generated using the VS .NET Integrated development Environment (IDE) has these queries.
Learn more about SqlCommand here: SqlCommand In ADO.NET. 

The Command Builder: 

10
The SQL SELECT command is a fairly easy one to construct. Even if you don’t know how to
construct a SQL SELECT command, the Query builder in visual studio helps you. But notice
there are three other commands in figure 3-6 to construct: InsertCommand, UpdateCommand,
and DeleteCommand. These commands can get quite complicated in .NET because they require
complex parameter objects and often involve large lists of columns ADO.NET provides a nice
utility known as the CommandBuilder that automatically builds these commands for you. 

The DataAdapter Object: 

The DataAdapter object serves as a conduit (tube, pipe) between the data source and the Dataset.
The DataAdapter knows about the DataSet and it knows how to populate it. The Adapter also
knows about the connection to the data source. Learn more about DataAdapter here:
DataAdapter in C#. 

DataSet Object: 

A DataSet object falls in disconnected components series. You can use it with or without data
providers. The DataSet consists of a collection of tables, rows, columns and relationships. Figure
3-10 illustrates these relationships specifically that the DataSet contains a collection of
DataTables and the DataTable contains a collection of DataRows, DataRelations, and
DataColumns. A DataTable maps to a table in the database. The previous DataSet contains a
DataTable that maps to the Orders table because you filled it with a SELECT query executed on
the Order table. 

Well, now you see how you can look at your tables, but you still really haven’t seen any hard
data yet. The data in a DataSet is contained in the DataRow. A DataTable in the DataSet consists
of a collection of DataRow. Each DataRow can be accessed via an index or the column name. As
you can see from figure 3-10, a data set has a one-to-many relationship with DataTable. That
means a DataSet can have one or more than one DataTable objects. Similarly, a DataTable can
have one or more than one DataRelation, DataRow, and DataColumn objects. Learn more about
DataSets here: DataSet in C# 

DataSets in DataViews: 

Another thing you can do with the contents of your DataSet is sort and filter them using
DataViews. You can have multiple Views of a dataset. A DataView is a view of your data
created according to certain criteria. Each DataView has a one-to-one mapping to a DataTable in
a DataSet. For example, say you have three tables in a dataset: table 1, table2, and table3. Using
three different data tables and data views, you can represent this dataset in three different views.
Using sort and filters, you can even sort and filter the data based on some criteria. A dataview
can directly attach to data-bound controls such as a DataGrid, DataList, or a Combo box. Learn
more about DataView here: DataView in C#.

11
https://www.c-sharpcorner.com/article/exploring-connection-in-ado-net/

Exploring SqlConnection In ADO.NET

Introduction

SqlConnection in ADO.NET represents a connection to a SQL Server database. In this article,


we will learn in depth about SqlConnection class including what is SqlConnection, create a
connection, and use SqlConnection in C# and how to use ADO.NET classes to work with SQL
Server, MS Access, MySQL and Oracle databases.  

What is a connection in ADO.NET?

ADO.NET connection is an object that provides database connectivity and the entry point to a
database. When the connection of an object is instantiated, the constructor takes a connection
string that contains the information about the database server, server type, database name,
connection type, and database user credentials. Once the connection string is passed and the
connection object is created, you can establish a connection with the database. A connection
string is usually stored in the web.config file or app.config file of an application.

What namespace or provider is used for connection class?


ADO.NET provides connection to multiple providers. Each provider has a functionality to
connect with different database. Here is a list of data providers in ADO.NET and their purpose.

 Data Provider for SQL Server (System.Data.SqlClient).


 Data Provider for MS ACCESS (System.Data.OleDb).
 Data Provider for MYSQL (System.Data.Odbc).
 Data Provider for ORACLE (System.Data.OracleClient).

How to use connection class with this provider is given below-

 Connection object for SQL Server (SqlConnection).


 Connection object for MSACCESS (OleDbConnection).
 Connection object for MYSQL (OdbcConnaction).
 Connection object for ORACLE (OracleConnection). 

In the connection string: 

 Data Source: This identifies the Server name, which could be the local machine, machine
domain name or IP address
 Initial Catalog: This identifies the database name.
 Integrated Security: When you have started database authentication login with Windows
authentication, Integrated Security specifies Integrated Security=”True” in connection
string, else when you have started the database authentication login with Server
12
authentication Integrated Security specifies Integrated Security=”false” in the connection
string
 User Id: Name of the user configured in SQL Server.
 Password: Password matching SQL Server User ID.

 // add only useful and relevant namespace  
   
 using System;  
 using System.Data.SqlClient;  
 using System.Data;  
   
 namespace ConsoleCRM  
 {  
     class Ravi  
     {  
         //only declare the Ado classes hare not instantiate   
   
         SqlConnection _Con = null;  
         SqlCommand _cmd = null;  
         SqlDataReader rd = null;  
         SqlTransaction _Transation;  
   
         static void Main(string[] args)  
         {  
             //Now create object of Ravi class and call method to this object  
   
             Ravi _Ravi = new Ravi();  
             _Ravi.GetResult();  
             Console.ReadLine();  
         }  
         private void GetResult()  
         {  
             //Now instantiate connection with connection string  
            // in connection string single space is not supported then we add @ sign
with connection string  

_Con = new SqlConnection(@"Data Source=RaviSERVER\RaviSERVER;Initial Catalog=Empl
oyeeDatabase;User ID=sa");  
 ////we can also read connection string from WebConfig file 

//string _StrCon = System.Configuration.ConfigurationManager.ConnectionStrings ["Constr"].C
onnectionString;   
 //_Con = new SqlConnection (_StrCon);  
   

13
             //Pass the connection with command object
             _cmd = new SqlCommand("select * from Product", _Con);  
             //Now check if current connection is closed then further its open   
             try  
             {  

if (_Con.State == ConnectionState.Closed)//ConnectionState is enum its    comes under System.
Data name space   
                 {  
                     _Con.Open();  
                 }  
                 //Use the connection and get result from database  
                 //Now start to current transaction  
                 _Con.BeginTransaction();  
                 rd = _cmd.ExecuteReader();  
                 // Read ProductId from each record  
                 while (rd.Read())  
                 {  
                     Console.WriteLine(rd["PrductId"]);  
                 }  
   
                 //Commit current transaction  
                 _Transation.Commit();  
             }  
             catch (SqlException Ex)  
             {  
                 //RollBack Transaction after any conflict occur  
                 _Transation.Rollback();  
             } 

// Now check current connection its open or close if connection is open then finally it's closed.  
             finally  
             {  
                 if (_Con.State == ConnectionState.Open)  
                     _Con.Close();  
             }  
         }  
     }  
 } 

As shown in the above code snippet, first of all, we declare a SqlConnection class. It is defined
in the System.Data.SqlClient namespace. Notice, when connection instantiation is required, we
will instantiate with a connection string. Now, connection is successfully established and you
open a connection by calling the Open() method of the SqlConnection object. In case, any

14
operation on connection is performing that connection will not yet open and will generate
exception. You must open connection before using it.

Notice, in case your current connection is already open, it must be closed before opening the
current connection. 
Thus, after connection opens, you pass connection with SqlCommand class. You can perform
any operation like (select, insert, update delete) by query or procedure with SqlCommend class.
Learn how to work with Command objects in ADO.NET.

Finally, your transition is successfully completed and you will close the connection by calling
the Close () method of the SqlConnection object is called in final blocks and we ensure that the
connection is not null before close.

Notice, we wrapped ADO.NET code in a try/finally block. The finally block helps guarantee that
a certain piece of code will be executed no matter what. Database connections are costly
resources so we must close them.  
If you want to learn more about try catch finally, visit Try..catch..finally in C# 

https://www.c-sharpcorner.com/UploadFile/c5c6e2/working-with-command-object/

Working With Command Object in ADO.NET

In this article, we will learn how to work with the Command Object in ADO .NET and the
Execute Methods in the Command Object. 

Command Object 
The command object is one of the basic components of ADO .NET.

1. The Command Object uses the connection object to execute SQL queries.
2. The queries can be in the Form of Inline text, Stored Procedures or direct Table access.
3. An important feature of Command object is that it can be used to execute queries and
Stored Procedures with Parameters.
4. If a select query is issued, the result set it returns is usually stored in either a DataSet or a
DataReader object.

Associated Properties of SqlCommand class


 
The properties associated with SqlCommand class are shown in the Table below.
 
Type of
Property Description
Access
Connection Read/Write The SqlConnection object that is used by the command object

15
to execute SQL queries or Stored Procedure.
Represents the T-SQL Statement or the name of the Stored
CommandText Read/Write Procedure.
 
This property indicates how the CommandText property should
be interpreted. The possible values are:

CommandType Read/Write 1. Text (T-SQL Statement)


2. StoredProcedure (Stored Procedure Name)
3. TableDirect

This property indicates the time to wait when executing a


particular command.
 
CommandTimeou
Read/Write Default Time for Execution of Command is 30 Seconds.
t
 
The Command is aborted after it times out and an exception is
thrown.
 
Now, Let us have a look at various Execute Methods that can be called from a Command Object.
 
Property Description
This method executes the command specifies and returns the number of
ExecuteNonQuery
rows affected.
The ExecuteReader method executes the command specified and returns an
ExecuteReader
instance of SqlDataReader class.
This method executes the command specified and returns the first column
ExecuteScalar
of first row of the result set. The remaining rows and column are ignored.
This method executes the command specified and returns an instance of
ExecuteXMLReade
XmlReader class. This method can be used to return the result set in the
r
form of an XML document
 
These are quite often methods in the Command objects. Let us now see each of these with an
example

Next Article:

https://www.c-sharpcorner.com/UploadFile/puranindia/try-catch-finally-in-C-Sharp/

16
The try..catch..finally block in .NET allows developers to handle runtime exceptions. The syntax
has three variations, try..catch, try..finally, and try..catch..finally. Learn more here: Exception
Handling in C#

The code example shows a try catch finally block syntax. 

1. try  
2. {  
3. //Put suspected code here. When an exception occurs, the control will move to the catch
block
4. }  
5. catch  
6. {  
7. //Catch the exception  
8. }  
9. finally  
10. {  
11. //this block of code will always get executed whether an  
12. // exception occurs or not as long as there are no exceptions  
13. // within this block itself. If an Exception is thrown here  
14. // some outer try block should handle it  
15. //Any Clean up code goes here. Especially to release any  
16. //system resources such as file handles and network  
17. //connections  
18. } 

https://www.c-sharpcorner.com/UploadFile/61b832/datareader-vs-dataset/

DataReader Vs DataSet?

DataSet and DataReader are two common components of ADO.NET that are used to get and
store data in a C# application. Let's learn the difference between the two and when to use a
DataSet vs a DataReader.
 
DataReader:

1. The ADO.NET DataReader is used to retrieve read-only (cannot update data back to a
datasource) and forward-only (cannot read backward/random) data from a database.
2. Using of a DataReader increases application performance and reduces system overheads.
This is due to one row at a time is stored in memory. 
3. You create a DataReader by calling Command.ExecuteReader after creating an instance
of the Command object. 

17
4. This is a connected architecture: The data is available as long as the connection with
database exists.
5. You need to open and close the connecton manually in code.

The following code statement is used to retrieve rows from a data source.

1. //opening connection is must  
2. conn.open();  
3. string SQLquery = "SELECT CustomerID, CompanyName FROM dbo.Customers";  
4. SqlCommand cmd = new SqlCommand(SQLquery, conn);  
5. // Call ExecuteReader to return a DataReader  
6. SqlDataReader myReader = cmd.ExecuteReader();  
7. //The Read method of the DataReader object is used to obtain a row from the results of 
8. //the executed query.   
9. while(myReader.Read())  
10. {  
11.     Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));  
12. }  
13. //Once you're done with the data reader, call the Close method to close a data reader:  
14. myReader.Close();  
15. //close the connection  
16. conn.close();  

DataSet

1. The DataSet is a in-memory representation of data. 


2. It can be used with multiple data sources. That is A single DataSet can hold the data from
different data sources holdng data from different databases/tables.
3. The DataSet represents a complete set of data including related tables, constraints, and
relationships among the tables. 
4. The DataSet can also persist and reload its contents as XML and its schema as XML
Schema definition language (XSD) schema.
5. The DataAdapter acts as a bridge between a DataSet and a data source for retrieving and
saving data. 
6. The DataAdapter helps mapping the data in the DataSet to match the data in the data
source. 
7. Also, Upon an update of dataset, it allows changing the data in the data source to match
the data in the DataSet. 
8. No need to manually open and close connection in code.
9. Hence, point (8) says that it is a disconnected architecture. Fill the data in DataSet and
that's it. No connection existence required

The following code statement is used to retrieve rows from a data source.

18
1. string SQLquery = "SELECT CustomerID, CompanyName FROM dbo.Customers";  
2. // create DataSet that will hold your Tables/data  
3. DataSet ds = new DataSet("CustomerDataSet");  
4. //Create SqlDataAdapter which acts as bridge to put the data in DataSet,(data is table avai
//lable by executing your SQL query)  
5. SqlDataAdapter myAdapter = new SqlDataAdapter(SQLquery, conn);  
6. //fill the dataset with the data by some name say "CustomersTable"  
7. myAdapter.Fill(ds,"CustomersTable");  

Here is a detailed tutorial on DataSet: DataSet in C#

https://www.c-sharpcorner.com/blogs/difference-between-datareader-dataset-dataadapter-and-
datatable-in-c-sharp1

Difference Between DataReader, DataSet, DataAdapter and


DataTable in C#
DataReader, DataSet, DataAdapter, and DataTable are four major components of ADO.NET. In
this blog, I will explain the difference between a DataReader, DataSet, DataAdapter, and
DataTable with code examples in C#.

DataReader:

DataReader is used to read the data from the database and it is a read and forward only
connection oriented architecture during fetch the data from database. DataReader will fetch the
data very fast when compared with dataset. Generally, we will use ExecuteReader object to bind
data to datareader.

To bind DataReader data to GridView we need to write the code like as shown below: 

1.protected void BindGridview() {


2.using(SqlConnection conn = new SqlConnection("Data
Source=abc;Integrated Security=true;Initial
Catalog=Test")) {
3.con.Open();
4.SqlCommand cmd = new SqlCommand("Select UserName,
First Name,LastName,Location FROM Users", conn);
5.SqlDataReader sdr = cmd.ExecuteReader();
6.gvUserInfo.DataSource = sdr;
7.gvUserInfo.DataBind();
8. conn.Close();

19
 Holds the connection open until you are finished (don't forget to close it!).
 Can typically only be iterated over once
 Is not as useful for updating back to the database

Here is a detailed tutorial on DataReader: DataReader in ADO.NET

DataSet:

DataSet is a disconnected orient architecture that means there is no need of active connections
during work with datasets and it is a collection of DataTables and relations between tables. It is
used to hold multiple tables with data. You can select data form tables, create views based on
table and ask child rows over relations. Also DataSet provides you with rich features like saving
data as XML and loading XML data. 

1. protected void BindGridview() {


2. SqlConnection conn = new SqlConnection("Data Source=abc;Integrated
Security=true;Initial Catalog=Test");
3. conn.Open();
4. SqlCommand cmd = new SqlCommand("Select UserName, First
Name,LastName,Location FROM Users", conn);
5. SqlDataAdapter sda = new SqlDataAdapter(cmd);
6. DataSet ds = new DataSet();
7. sda.Fill(ds);
8. gvUserInfo.DataSource = ds;
9. gvUserInfo.DataBind();
10. }

DataAdapter:

DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used
to read the data from database and bind that data to dataset. Dataadapter is a disconnected
oriented architecture. Check below sample code to see how to use DataAdapter in code: 

1. protected void BindGridview() {


2. SqlConnection con = new SqlConnection("Data Source=abc;Integrated
Security=true;Initial Catalog=Test");
3. conn.Open();
4. SqlCommand cmd = new SqlCommand("Select UserName, First
Name,LastName,Location FROM Users", conn);
5. SqlDataAdapter sda = new SqlDataAdapter(cmd);
6. DataSet ds = new DataSet();
7. sda.Fill(ds);
8. gvUserInfo.DataSource = ds;
9. gvUserInfo.DataBind();
10. }

20
 Lets you close the connection as soon it's done loading data, and may even close it for
you automatically
 All of the results are available in memory
 You can iterate over it as many times as you need, or even look up a specific record by
index
 Has some built-in faculties for updating back to the database.

Here is a detailed tutorial on DataAdapter: DataAdapter in C#

DataTable:

DataTable represents a single table in the database. It has rows and columns. There is no much
difference between dataset and datatable, dataset is simply the collection of datatables. 

1. protected void BindGridview()


2. {
3. SqlConnection con = new SqlConnection("Data Source=abc;Integrated
Security=true;Initial Catalog=Test");
4. conn.Open();
5. SqlCommand cmd = new SqlCommand("Select UserName, First
Name,LastName,Location FROM Users", conn);
6. SqlDataAdapter sda = new SqlDataAdapter(cmd);
7. DataTable dt = new DataTable();
8. sda.Fill(dt);
9. gridview1.DataSource = dt;
10. gvidview1.DataBind();
11. }

Here is a detailed tutorial in DataTable: DataTable in C#

https://www.c-sharpcorner.com/UploadFile/e95fe7/introduction-to-ado-net/

Introduction to ADO.Net
Introducing ADO.NET 
This article introduces the ADO.Net object model. In addition, it explains how to create and
manage connections to a database.

Introduction to ADO.NET

Most applications need to handle data, whether it is in the form of a dataset, a text file, or a
spreadsheet. The majority of modern-day applications need to deal with various types of

21
databases. Therefore, to access this data the application needs to interact with various databases,
such as Microsoft SQL Server, Oracle, Microsoft Access and so on.  

What ADO.NET is 


ADO.NET is a large set of .NET classes that enable us to retrieve and manipulate data, and
update data sources, in very many ways. As an integral part of the .NET framework, it shares
many of its features; features such as multi-language support, garbage collection, just-in-time
compilation, object-oriented design, and dynamic caching, and is far more than an upgrade of
previous versions of ADO. ADO.NET is set to become a core component of any data-driven
.NET application or Web Service, and understanding its power will be essential to anyone
wishing to utilize .NET data support to maximum effect.

ADO.NET is a part of the .NET framework architecture. It is a model used by .NET applications
to communicate with a database for retrieving, accessing, and updating data, as shown in the
following figure: 

ADO.NET Object Model 


In the ADO.NET object model, the data residing in a database is retrieved through a data
provider. The data provider is the set of components including the Connection, Command,
DataReader, and DataAdapter objects. An application can access data either through a dataset
or through a datareader object. 

22
The ADO.NET object model consists of two fundamental components:

 Data Provider
 DataSet

Data Provider: 
Selecting an appropriate data provider for a client application depends on the type of data source
being accessed. There are four .Net data providers available.

1. SQL Server: It's used to work specifically with Microsoft SQL Server. It exists in a
namespace within the System.Data.SqlClient.
2. OLE DB: It's used to work with the OLEDB provider. The System.Data.dll assembly
implements the OLEDB .NET framework data provider in the System.Data.OleDb
namespace.
3. ODBC: To use this type of provider, you must use an ODBC driver. The
System.Data.ODBC.dll assembly implements the ODBC .NET framework data provider.
This assembly is not part of the Visual Studio .NET installation.
4. Oracle: The System.Data.OracleClient.dll assembly implements the Oracle  .NET
framework data provider in the System.Data.OracleClient namespace. The Oracle client
software must be installed on the system before you can use the provider to connect to an
Oracle data source.

Data Provider Components: 


The four key components of a dataprovider are:

1. Connection: Used to connect to the data source.


2. Command: Used to execute a command against the data source. This component
retrieves, inserts, deletes, and modifies data in a data source.
3. DataReader: This component retrieves data from a data source in read-only and forward
mode.
4. DataAdapter: Used to populate a dataset with the data retrived from a database and  to
update the data source.

23
 

DataSet: 
DataSet is a part of a disconnected architecture. A DataSet is a cached memory of data retrieved 
from a database. DataSet is present in the  System.Data namespace. In order to connect a DataSet
to a data source, we need to use a DataAdapter.  

Creating and Managing Connections In ADO.NET  


Creating a Connection object: 
The connection component of a dataprovider establishes a connection with a data base. To
connect to a Microsoft SQL Server, you use the SQL connection class. The following are the
commonly used properties and Methods of the SqlConnection class.

1. ConnectionString: provides information, such as database name and, user credentials for
database access and so on.
2. Open():  Opens the connection for accessing the database. 
3. Close(): Closes the connection to the database.

For Example:
1. // Creating object of SqlConnection Class.  
2. SqlConnection cn = new SqlConnection();  
3.   
4. //Creating connection string to sample database.  
5. cn.ConnectionString = "Data source=.; Initial Catalog=Sample; User Id=sa; Password=fa
culty";  
6. cn.Open(); // it open the connection to database server..  

24
7.   
8. //Creating sqlcommand class object  
9. SqlCommand cmd = new SqlCommand("Select * from tblEmployees", cn);  
10. SqlDataReader dr = cmd.ExecuteReader(); //Executing query  
11. cn.Close(); //Closing the connection 

The connection string provides the information that defines the connection to the database.

 Data Source: Specifies the provider name or your server name.


 Initial Catalog: Specifies the name of the database.
 User Id and Password: Provide the username and password of your database server.

Let's do one demo


 
Consider the situation in which you are working in XYZ inc. as an application developer. As a
member of the development team, you have been asked to develop an application that will
display all the records from tblEmployee table present in the sample database.
 
Note: In this example I'm using a sample database present in my datasource. Here you need to
create a sample database and the tblEmployee table in that database, and populate the
tblEmployee table with some values.
 
Step 1: Create a Windows Form application and design the form as shown in the following
figure.
 

25
 
Step 2: Add the following two namespaces:

 System.Data.SqlClient;
 System.Data;

Step 3: On click event of the Button write the following code:

1. SqlConnection cn = new SqlConnection();  
2.   
3. //Creating connection string to sample database.  
4. cn.ConnectionString = "Data source=.; Initial Catalog=Sample; User Id=sa; Password=fa
culty";  
5.   
6. //Open Connection  
7. cn.Open();  
8.   
9. //Creating SqlCommand class Object  
10. SqlCommand cmd = new SqlCommand("Select * from tblEmployee", cn);  
11.   
12. //Creating Object of dataAdapter  
13. SqlDataAdapter da = new SqlDataAdapter();  
14.   
15. //Creating object of dataSet  
16. DataSet ds = new DataSet();  
17. da.SelectCommand = cmd;  
18.   
19. //Populating dataset by using fill method of sqldataAdapter  
20. da.Fill(ds);  
21.   
22. //Binding dataset with DataGrideview1 control  
23. GridView1.DataSource = ds.Tables[0]; 

Note: We will see more about SqldataAdpter's methods and properties in my future articles on
ADO.NET.
 
Step 4: Execute the application and verify the output by clicking on the button control. If
everything goes fine then you will get the following output:
 

26
 
In the next article we will see DataBinding and filter records in ADO.NET.

https://www.completecsharptutorial.com/ado-net/datareader-ado-net-c-programming-
example.php

DataReader ADO.Net C# - Programming Example


In this tutorial, you will learn

1. What is DataReaders?
2. How to use DataReaders in ADO.NET for retrieving data?
3. Programming Examples

What is DataReaders?

The DataReader object in C# ADO.NET allows you to retrieve data from database in read-only
and forward-only mode. It means you can only read and display data but can’t update or delete
data. If you want to make modification in retrieved data you need to use DataAdapter instead of
DataReader.

Why and When to Use DataReader?

When you want to only display information or search result, you can use DataReader. There are
various advantages of using DataReader like:

27
1. The retrieved data is stored in the network buffer in the client and then the client can read data
using Read method. As data gets stored in the client network buffer it increases application
performance significantly.

2. By default, DataReader stores only one row at a time in memory. It reduces system overhead.

Methods and Properties of 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

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 value from a
Getxxx column. For example. GetChar will return a column value as a character and GetString as a
string.

1. using System;
2. using System.Data.SqlClient;
3.  
4. namespace DataReader_Examples
5. {
6. class Program
7. {
8. static void Main(string[] args)
9. {
10. string ConString = @"Data Source=.\SQLEXPRESS;Initial
Catalog=ComputerShop;Integrated Security=True";
11. SqlConnection con = new SqlConnection(ConString);
12. string querystring = "Select * from Items";
13. try
14. {

28
15. con.Open();
16. SqlCommand cmd = new SqlCommand(querystring, con);
17. SqlDataReader reader = cmd.ExecuteReader();
18. while (reader.Read())
19. {
20. Console.WriteLine(reader[0].ToString() + " " +
reader[1].ToString() + " " + reader[2].ToString());
21. }
22.
23. }
24. catch(SqlException ex)
25. {
26. Console.WriteLine(ex.ToString());
27. }
28. finally
29. {
30. con.Close();
31. Console.ReadKey();
32. }
33. }
34. }
35. }

Summary:

In this tutorial, you learned how to use DataReader in ADO.NET for accessing data from
database table. In the next chapter, you will learn about DataAdapters and DataSets.

DataSet Tutorial with C# ADO.Net Programming Example


https://www.completecsharptutorial.com/ado-net/dataset-tutorial-with-c-ado-net-programming-
example.php

In this tutorial, you will learn:


1. What is DataSet in ADO.Net?
2. What is DataAdapters?
3. DataAdapters Properties and Methods.
4. Programming Example

Content of this Article:

 What is DataSet and DataAdapters in ADO.Net?


 Fill DataSet and Show in GridView
 Updating, Inserting and Deleting rows in DataSet.

29
 Save DataSet Changes to Database.

What is DataSet in ADO.NET?

In a simple word, A DataSet is a local copy of your Database Table that gets populated in client
PC. It is independent of Data Source and because it exists in the local system, it makes
application fast and reliable. Accessing Remote Database each time for updating or retrieving
details are time-consuming so datasets help you to keep local database tables on your PC.

A DataSet behaves like real Database and it represents a complete set of data that includes tables,
constraints, and relationships among the tables. Using the DataAdapters you can fill DataSet
and use this dataset for retrieving and storing information. When all the tasks get completed,
update Real Database with datasets.

What is DataAdapters?

DataAdapters are used for controlling Datasets and it provides communication between
DataSets and DataSource. DataAdapters make a connection with Data Source and then Fill Data
to DataSets. It also Updates Data Source with DataSets.

Important Data Adapters Properties and Methods:

Properties:
Properties Description

DeleteCommand It is used for Deleting Records from DataSource

InsertCommand It is used for adding New Record to a DataSource

SelectCommand It is used for Selecting Records from a DataSource

UpdateCommand It is used for Updating Records in a DataSource.

TableMapping It is used for mapping actual database tables and datasets.

Methods:
Method Description

Fill This method Fills Records from DataAdapters to DataSets.

Update This method update DataSource with DataSets.

Programming Example in C# Console:

1. using System;

30
2. using System.Data.SqlClient;
3. using System.Data;
4.  
5. namespace DataSet_Example
6. {
7. class Program
8. {
9. static void Main(string[] args)
10. {
11. string ConString = @"Data Source=.\SQLEXPRESS;Initial
Catalog=ComputerShop;Integrated Security=True";
12. string querystring = "Select * from Items";
13. SqlDataAdapter adapter = new SqlDataAdapter(querystring,
ConString);
14. DataSet ds = new DataSet();
15. adapter.Fill(ds, "Items");
16. Console.WriteLine(ds.GetXml());
17. Console.ReadKey();
18. }
19. }
20. }

DataSet Example with Grid View:

Mostly DataSet is used with GridView in ASP.Net. Here, I have explained DataAdapters and
DataSets with Examples.

1. Open Visual Studio 2015 and Go to File > New >


Project. Create a New Windows Forms Application Dataset_Example.

31
2. Drag a GridView and a Button like that.

32
Extract Data from DataSet to GridView
1. using System;
2. using System.Data;
3. using System.Data.SqlClient;
4. using System.Windows.Forms;
5.  
6. namespace DataSet_Exampl
7. {
8. public partial class Form1 : Form
9. {
10. public Form1()
11. {
12. InitializeComponent();
13. }
14.  
15. private void btnGetData_Click(object sender, EventArgs
e)
16. {
17. string ConString = @"Data
Source=.\SQLEXPRESS;Initial Catalog=ComputerShop;Integrated
Security=True";
18. string Query = "SELECT * FROM Items";
19.  
20. SqlDataAdapter adapter = new
SqlDataAdapter(Query,ConString);
21. DataSet set = new DataSet();
22.  
23. adapter.Fill(set, "Items");
24. dataGridView1.DataSource = set.Tables["Items"];
25. }
26. }
27. }

Output:

33
Updating, Inserting, and Deleting Records in a Dataset

After populating dataset, you can update, insert or delete a record from the dataset. Here is a full
programming example.

Adding New Row in DataTable


1. private void btnInsert_Click(object sender, EventArgs e)
2. {
3. //Fill Dataset
4. string ConString = @"Data Source=.\SQLEXPRESS;Initial
Catalog=ComputerShop;Integrated Security=True";
5. string Query = "SELECT * FROM Items";
6. SqlDataAdapter adapter = new SqlDataAdapter(Query,
ConString);
7. DataSet set = new DataSet();
8. adapter.Fill(set, "Items");
9.
10. //Adding New Row to DataSet
11. DataRow row = set.Tables["Items"].NewRow();
12. row["Name"] = "4GB DDR3 RAM";
13. row["Price"] = "$50";
14. row["Date"] = "26 May 2017";
15. set.Tables["Items"].Rows.Add(row);
16.
17. dataGridView1.DataSource = set.Tables["Items"];
18. }

Output

34
Insert Row in Dataset

Edit or Update Row in DataSet

If you don’t know row index or unique row number still you can update or edit row in dataset by
using following method.

1. private void btnUpdate_Click(object sender, EventArgs e)


2. {
3. //Fill Dataset
4. string ConString = @"Data Source=.\SQLEXPRESS;Initial
Catalog=ComputerShop;Integrated Security=True";
5. string Query = "SELECT * FROM Items";
6. SqlDataAdapter adapter = new SqlDataAdapter(Query,
ConString);
7. DataSet set = new DataSet();
8. adapter.Fill(set, "Items");
9.  
10. set.Tables["Items"].Rows[1]["Name"] = "Graphics
Card";
11.  
12. dataGridView1.DataSource = set.Tables["Items"];
13. }

Output

35
Delete Row in DataSet

You can delete row from dataset using Delete() Method.

1. private void btnDelete_Click(object sender, EventArgs e)


2. {
3. //Fill Dataset
4. string ConString = @"Data Source=.\SQLEXPRESS;Initial
Catalog=ComputerShop;Integrated Security=True";
5. string Query = "SELECT * FROM Items";
6. SqlDataAdapter adapter = new SqlDataAdapter(Query,
ConString);
7. DataSet set = new DataSet();
8. adapter.Fill(set, "Items");
9.  
10. set.Tables["Items"].Rows[1].Delete();
11.  
12. dataGridView1.DataSource = set.Tables["Items"];
13. }

Output

36
Save Dataset Changes to Database

After Modifying Dataset, you can save Dataset changes to database.

Programming Example

1. private void btnSave_Click(object sender, EventArgs e)


2. {
3. //Fill Dataset
4. string ConString = @"Data Source=.\SQLEXPRESS;Initial
Catalog=ComputerShop;Integrated Security=True";
5. string Query = "SELECT * FROM Items";
6. SqlDataAdapter adapter = new SqlDataAdapter(Query,
ConString);
7. DataSet set = new DataSet();
8. adapter.Fill(set, "Items");
9.  
10. //Adding New Row to DataSet and Update
11. DataRow row = set.Tables["Items"].NewRow();
12. row["Name"] = "4GB DDR3 RAM";
13. row["Price"] = "$50";
14. row["Date"] = "26 May 2017";
15. set.Tables["Items"].Rows.Add(row);
16.  
17. //Updating Database Table
18. SqlCommandBuilder builder = new
SqlCommandBuilder(adapter);
19. adapter.Update(set.Tables["Items"]);
20.  
21. MessageBox.Show("DataSet Saved to Database Successfully");
22.
23. }

37
Output
DataSet Saved to Database Successfully _

Complete Program:
1. using System;
2. using System.Data;
3. using System.Data.SqlClient;
4. using System.Windows.Forms;
5.  
6. namespace DataSet_Exampl
7. {
8. public partial class Form1 : Form
9. {
10. public Form1()
11. {
12. InitializeComponent();
13. }
14.  
15. private void btnGetData_Click(object sender, EventArgs e)
16. {
17. //Fill DataSet
18. string ConString = @"Data Source=.\SQLEXPRESS;Initial
Catalog=ComputerShop;Integrated Security=True";
19. string Query = "SELECT * FROM Items";
20.  
21. SqlDataAdapter adapter = new
SqlDataAdapter(Query,ConString);
22. DataSet set = new DataSet();
23.  
24. adapter.Fill(set, "Items");
25. dataGridView1.DataSource = set.Tables["Items"];
26. }
27.  
28. private void btnUpdate_Click(object sender, EventArgs e)
29. {
30. //Fill Dataset
31. string ConString = @"Data Source=.\SQLEXPRESS;Initial
Catalog=ComputerShop;Integrated Security=True";
32. string Query = "SELECT * FROM Items";
33. SqlDataAdapter adapter = new SqlDataAdapter(Query,
ConString);
34. DataSet set = new DataSet();
35. adapter.Fill(set, "Items");
36.  
37. set.Tables["Items"].Rows[1]["Name"] = "Graphics Card";
38.  
39. dataGridView1.DataSource = set.Tables["Items"];
40. }
41.  
42. private void btnInsert_Click(object sender, EventArgs e)
43. {
44. //Fill Dataset
45. string ConString = @"Data Source=.\SQLEXPRESS;Initial
Catalog=ComputerShop;Integrated Security=True";
46. string Query = "SELECT * FROM Items";

38
47. SqlDataAdapter adapter = new SqlDataAdapter(Query,
ConString);
48. DataSet set = new DataSet();
49. adapter.Fill(set, "Items");
50.
51. //Adding New Row to DataSet
52. DataRow row = set.Tables["Items"].NewRow();
53. row["ID"] = 3;
54. row["Name"] = "4GB DDR3 RAM";
55. row["Price"] = "$50";
56. row["Date"] = "26 May 2017";
57. set.Tables["Items"].Rows.Add(row);
58.
59. dataGridView1.DataSource = set.Tables["Items"];
60. }
61.  
62. private void btnDelete_Click(object sender, EventArgs e)
63. {
64. //Fill Dataset
65. string ConString = @"Data Source=.\SQLEXPRESS;Initial
Catalog=ComputerShop;Integrated Security=True";
66. string Query = "SELECT * FROM Items";
67. SqlDataAdapter adapter = new SqlDataAdapter(Query,
ConString);
68. DataSet set = new DataSet();
69. adapter.Fill(set, "Items");
70.  
71. set.Tables["Items"].Rows[1].Delete();
72.  
73. dataGridView1.DataSource = set.Tables["Items"];
74. }
75.  
76. private void btnSave_Click(object sender, EventArgs e)
77. {
78. //Fill Dataset
79. string ConString = @"Data Source=.\SQLEXPRESS;Initial
Catalog=ComputerShop;Integrated Security=True";
80. string Query = "SELECT * FROM Items";
81. SqlDataAdapter adapter = new SqlDataAdapter(Query,
ConString);
82. DataSet set = new DataSet();
83. adapter.Fill(set, "Items");
84.  
85. //Adding New Row to DataSet and Update
86. DataRow row = set.Tables["Items"].NewRow();
87. row["Name"] = "4GB DDR3 RAM";
88. row["Price"] = "$50";
89. row["Date"] = "26 May 2017";
90. set.Tables["Items"].Rows.Add(row);
91.  
92. //Updating Database Table
93. SqlCommandBuilder builder = new
SqlCommandBuilder(adapter);
94. adapter.Update(set.Tables["Items"]);
95.  
96. MessageBox.Show("DataSet Saved to Database Successfully");
97.

39
98. }
99. }
100. }

Summary:

In this chapter, you learned how to work with DataSet and DataTable in C# ADO.Net. You can
locally work with the dataset and after completing all the modification, save back to the
database. In the next chapter, you will learn about DataTables and DataView.

https://www.completecsharptutorial.com/ado-net/dataviews-programming-tutorial-with-c-ado-
net.php

DataViews Programming Tutorial with C# ADO.Net


In this tutorial, you will learn:

1. What is DataViews in ADO.Net?


2. How to display data in DataViews?

What is DataViews?
DataView gives option to display DataTable’s data in various style, views or format. With
DataView you can display data with various sorting order, customization and filtration. In this
tutorial you will learn everything about DataView in C# ADO.Net.

Content of this Tutorial

1. Creating and Displaying a DataView


2. Sorting and Filtering DataView
3. Adding Row in DataView
4. Editing or Updating Row in DataView
5. Deleting Row from DataView
6. Complete Program

40
https://www.guru99.com/c-sharp-access-database.html

C# Database Connection: How to connect SQL Server (Example)


Accessing Data from a database is one of the important aspects of any programming language. It
is an absolute necessity for any programming language to have the ability to work with
databases. C# is no different.

It can work with different types of databases. It can work with the most common databases such
as Oracle and Microsoft SQL Server.

It also can work with new forms of databases such as MongoDB and MySQL.

In this C# sql connection tutorial, you will learn-

 Fundamentals of Database connectivity


 How to connect C# to Database
 Access data with the SqlDataReader

41
 C# Insert Into Database
 Updating Records
 Deleting Records
 Connecting Controls to Data
 C# DataGridView

Fundamentals of Database connectivity

C# and .Net can work with a majority of databases, the most common being Oracle and
Microsoft SQL Server. But with every database, the logic behind working with all of them is
mostly the same.

In our examples, we will look at working the Microsoft SQL Server as our database. For learning
purposes, one can download and use the Microsoft SQL Server Express Edition, which is a
free database software provided by Microsoft.

In working with databases, the following are the concepts which are common to all databases.

1. Connection – To work with the data in a database, the first obvious step is the
connection. The connection to a database normally consists of the below-mentioned
parameters.
1. Database name or Data Source – The first important parameter is the database
name to which the connection needs to be established. Each connection can only
work with one database at a time.
2. Credentials – The next important aspect is the username and password which
needs to be used to establish a connection to the database. It ensures that the
username and password have the necessary privileges to connect to the database.
3. Optional parameters – For each database type, you can specify optional
parameters to provide more information on how .net should handle the connection
to the database. For example, one can specify a parameter for how long the
connection should stay active. If no operation is performed for a specific period of
time, then the parameter would determine if the connection has to be closed.
2. Selecting data from the database – Once the connection has been established, the next
important aspect is to fetch the data from the database. C# can execute ‘SQL’ select
command against the database. The ‘SQL’ statement can be used to fetch data from a
specific table in the database.
3. Inserting data into the database – C# can also be used to insert records into the
database. Values can be specified in C# for each row that needs to be inserted into the
database.
4. Updating data into the database – C# can also be used to update existing records into
the database. New values can be specified in C# for each row that needs to be updated
into the database.

42
5. Deleting data from a database – C# can also be used to delete records into the database.
Select commands to specify which rows need to be deleted can be specified in C#.

Ok, now that we have seen the theory of each operation, let’s jump into the further
sections to look at how we can perform database operations in C#.

SQL Command in c#

SqlCommand in C# allow the user to query and send the commands to the database. SQL
command is specified by the SQL connection object. Two methods are used, ExecuteReader
method for results of query and ExecuteNonQuery for insert, Update, and delete commands. It is
the method that is best for the different commands.

How to connect C# to Database

Let’s now look at the code, which needs to be kept in place to create a connection to a database.
In our example, we will connect to a database which has the name of Demodb. The credentials
used to connect to the database are given below

 Username – sa
 Password – demo123

We will see a simple Windows forms application to work with databases. We will have a simple
button called “Connect” which will be used to connect to the database.

So let’s follow the below steps to achieve this:

Step 1) The first step involves the creation of a new project in Visual Studio. After launching
Visual Studio, you need to choose the menu option New->Project.

43
Step 2) The next step is to choose the project type as a Windows Forms application. Here, we
also need to mention the name and location of our project.

1. In the project dialog box, we can see various options for creating different types of
projects in Visual Studio. Click the Windows option on the left-hand side.
2. When we click the Windows options in the previous step, we will be able to see an option
for Windows Forms Application. Click this option.

44
3. We then give a name for the application which in our case is “DemoApplication”. We
also need to provide a location to store our application.
4. Finally, we click the ‘OK’ button to let Visual Studio to create our project.

Step 3) Now add a button from the toolbox to the Windows form. Put the text property of the
Button as Connect. This is how it will look like

Step 4) Now double click the form so that an event handler is added to the code for the button
click event. In the event handler, add the below code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

45
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DemoApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString;
SqlConnection cnn;
connetionString = @"Data Source=WIN-50GP30FGO75;Initial
Catalog=Demodb;User ID=sa;Password=demol23";
cnn = new SqlConnection(connetionString);
cnn.Open();
MessageBox.Show("Connection Open !");
cnn.Close();
}
}
}

Code Explanation: -

1. The first step is to create variables, which will be used to create the connection string and
the connection to the SQL Server database.
2. The next step is to create the connection string. The connecting string needs to be
specified correctly for C# to understand the connection string. The connection string
consists of the following parts
1. Data Source – This is the name of the server on which the database resides. In our
case, it resides on a machine called WIN- 50GP30FGO75.
2. The Initial Catalog is used to specify the name of the database
3. The UserID and Password are the credentials required to connect to the database.
3. Next, we assign the connecting string to the variable cnn. The variable cnn, which is of
type SqlConnection is used to establish the connection to the database.
4. Next, we use the Open method of the cnn variable to open a connection to the database.
We then just display a message to the user that the connection is established.

46
5. Once the operation is completed successfully, we then close the connection to the
database. It is always a good practice to close the connection to the database if nothing
else is required to be done on the database.

When the above code is set, and the project is executed using Visual Studio, you will get the
below output. Once the form is displayed, click the Connect button.

Output: -

When you click on “connect” button, from the output, you can see that the database connection
was established. Hence, the message box was displayed.

Access data with the SqlDataReader:

To showcase how data can be accessed using C#, let us assume that we have the following
artifacts in our database.

1. A table called demotb. This table will be used to store the ID and names of various
Tutorials.
2. The table will have 2 columns, one called “TutorialID” and the other called
“TutorialName.”
3. For the moment, the table will have 2 rows as shown below.

TutorialID TutorialName

1 C#

2 ASP.Net

47
Let’s change the code in our form, so that we can query for this data and display the information
via a Messagebox. Note that all the code entered below is a continuation of the code written for
the data connection in the previous section.

Step 1) Let’s split the code into 2 parts so that it will be easy to understand for the user.

 The first will be to construct our “select” statement, which will be used to read the data
from the database.
 We will then execute the “select” statement against the database and fetch all the table
rows accordingly.

Code Explanation:-

1. The first step is to create the following variables


1. SQLCommand – The ‘SQLCommand’ is a class defined within C#. This class is
used to perform operations of reading and writing into the database. Hence, the
first step is to make sure that we create a variable type of this class. This variable
will then be used in subsequent steps of reading data from our database.
2. The DataReader object is used to get all the data specified by the SQL query. We
can then read all the table rows one by one using the data reader.
3. We then define 2 string variables, one is “SQL” to hold our SQL command string.
The next is the “Output” which will contain all the table values.
2. The next step is to define the SQL statement, which will be used against our database. In
our case, it is “Select TutorialID, TutorialName from demotb”. This will fetch all the
rows from the table demotb.
3. Next, we create the command object which is used to execute the SQL statement against
the database. In the SQL command, you have to pass the connection object and the SQL
string.

48
4. Next, we will execute the data reader command, which will fetch all the rows from the
demotb table.
5. Now that we have all the rows of the table with us, we need a mechanism to access the
row one by one. For this, we will use the while statement. The while statement will be
used to access the rows from the data reader one at a time. We then use the GetValue
method to get the value of TutorialID and TutorialName.

Step 2) In the final step, we will just display the output to the user and close all the objects
related to the database operation.

Code Explanation:-

1. We will continue our code by displaying the value of the Output variable using the
MessageBox. The Output variable will contain all the values from the demotb table.
2. We finally close all the objects related to our database operation. Remember this is
always a good practice.

When the above code is set, and the project is run using Visual Studio, you will get the below
output. Once the form is displayed, click the Connect button.

Output: -

49
From the output, you can clearly see that the program was able to get the values from the
database. The data is then displayed in the message box.

C# Insert Into Database

Just like Accessing data, C# has the ability to insert records into the database as well. To
showcase how to insert records into our database, let’s take the same table structure which was
used above.

TutorialID TutorialName

1 C#

2 ASP.Net

Let’s change the code in our form, so that we can insert the following row into the table

TutorialID TutorialName

3 VB.Net

So let’s add the following code to our program. The below code snippet will be used to insert an
existing record in our database.

50
Code Explanation:-

1. The first step is to create the following variables


1. SQLCommand – This data type is used to define objects which are used to
perform SQL operations against a database. This object will hold the SQL
command which will run against our SQL Server database.
2. The DataAdapter object is used to perform specific SQL operations such as insert,
delete and update commands.
3. We then define a string variable, which is “SQL” to hold our SQL command
string.
2. The next step is to actually define the SQL statement which will be used against our
database. In our case, we are issuing an insert statement, which will insert the record of
TutorialID=1 and TutorialName=VB.Net
3. Next, we create the command object which is used to execute the SQL statement against
the database. In the SQL command, you have to pass the connection object and the SQL
string
4. In our data adapter command, we now associate the insert SQL command to our adapter.
We also then issue the ExecuteNonQuery method which is used to execute the Insert
statement against our database. The ‘ExecuteNonQuery’ method is used in C# to issue
any DML statements against the database. By DML statements, we mean the insert,
delete, and update operation. In C# , if you want to issue any of these statements against a
table, you need to use the ExecuteNonQuery method.
5. We finally close all the objects related to our database operation. Remember this is
always a good practice.

51
When the above code is set, and the project is executed using Visual Studio, you will get the
below output. Once the form is displayed, click the Connect button.

Output:-

If you go to SQL Server Express and see the rows in the demotb table, you will see the row
inserted as shown below:

C# Update Database

52
More Reading:

https://www.c-sharpcorner.com/UploadFile/d0a1c8/database-programming-with-ado-net/

https://www.oreilly.com/library/view/adonet-in-a/0596003617/ch01s01.html

https://www.javatpoint.com/ado-net-tutorial

https://www.c-sharpcorner.com/article/introduction-to-ado-net/

https://www.c-sharpcorner.com/UploadFile/8a67c0/different-ways-to-access-database-in-ado-
net/

https://www.codeproject.com/Articles/361579/A-Beginners-Tutorial-for-Understanding-ADO-
NET

https://www.codeproject.com/Articles/8477/Using-ADO-NET-for-Beginners

53

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy