Intro To
Intro To
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.
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).
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#.
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.
3
This contains key and value pairs, like provider, server, database, userid and word as in the
following:
SQL Authentication
Or:
Windows Authentication
String constr="server=.;database=institute;trusted_connection=true"
Or:
2. Handle exceptions.
6. Get the Result (use SqlDataReader). This is a forward only/read only data object.
4
8. Process the result
9. Display the Result
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.
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.
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.
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 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 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.
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.
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#
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.
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 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/
Introduction
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.
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/
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.
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:
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#
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
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");
https://www.c-sharpcorner.com/blogs/difference-between-datareader-dataset-dataadapter-and-
datatable-in-c-sharp1
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:
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
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.
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:
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.
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.
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.
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:
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.
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.
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.
25
Step 2: Add the following two namespaces:
System.Data.SqlClient;
System.Data;
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
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.
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
METHOD DESCRIPTION
NextResult Advances the data reader to the next result during batch transactions.
There are dozens of Getxxx methods. These methods read a specific data type 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.
29
Save DataSet Changes to Database.
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.
Properties:
Properties Description
Methods:
Method Description
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. }
Mostly DataSet is used with GridView in ASP.Net. Here, I have explained DataAdapters and
DataSets with Examples.
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.
Output
34
Insert 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.
Output
35
Delete Row in DataSet
Output
36
Save Dataset Changes to Database
Programming Example
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
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.
40
https://www.guru99.com/c-sharp-access-database.html
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.
41
C# Insert Into Database
Updating Records
Deleting Records
Connecting Controls to Data
C# DataGridView
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.
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.
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();
}
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.
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:-
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.
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:-
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