Notesss
Notesss
AND.NET
INTRODUCTION
ADO.NET is a set of classes that allows you to connect and work with data sources
like databases, excel file, access file, xml file, mysql, sql or notepad. To connect your
application with different sources of database you need to know the right Data
Provider. There are several Data Providers in ADO.NET that connects with different
We know that ADO.NET allows us to interact with different types of data sources
and different types of databases. However, there isn’t a single set of classes that
allow you to accomplish this universally. Since different data sources expose
different protocols, we need a way to communicate with the right data source using
the right protocol Some older data sources use the ODBC protocol, many newer data
sources use the OleDb protocol, and there are more data sources every day that
allow you to communicate with them directly through .NET ADO.NET class libraries.
ADO.NET provides a relatively common way to interact with data sources but comes
in different sets of libraries for each way you can talk to a data source. These
libraries are called Data Providers and are usually named for the protocol or data
source type they allow you to interact with. The table below lists some well-known
data providers, the API prefix they use, and the type of data source they allow you
to interact with.
Oracle Data
Oracle For Oracle Databases.
Provider
SQL Data
SQL For interacting with Microsoft SQL Server.
Provider
There are 4 Core Components of .Net Data Providers that is used to connect, access
1. Connection – This component is used for connecting to the database. The base
class is DbConnection.
2. Command – This component executes SQL query against the data source. The base
class is DbCommand.
3. DataReader – It reads data from data source. It accesses data read-only and
ADO.NET Objects
ADO.NET includes many objects you can use to work with data. This section
introduces some of the primary objects you will use. The objects below are the ones
you must know. Learning about them will give you an idea of the types of things you
To interact with a database, you must have a connection to it. The connection helps
identify the database server, the database name, username, password, and other
parameters that are required for connecting to the database. A connection object
is used by command objects so they will know which database to execute the
command on.
The process of interacting with a database means that you must specify the actions
you want to occur. This is done with a command object. You use a command object to
send SQL statements to the database. A command object uses a connection object
Many data operations require that you only get a stream of data for reading. The
data reader object allows you to obtain the results of a SELECT statement from a
command object. For performance reasons, the data returned from a data reader is
the stream in a sequential manner. This is good for speed, but if you need to
Datatable objects, which contain columns and rows, just like normal database tables.
You can even define relations between tables to create parent-child relationships.
The DataSet is specifically designed to help manage data in memory and to support
disconnected operations on data when such a scenario make sense. The DataSet is
an object that is used by all of the Data Providers, which is why it does not have a
Sometimes the data you work with is primarily read-only and you rarely need to make
changes to the underlying data source. Some situations also call for caching data in
memory to minimize the number of database calls for data that does not change. The
data adapter makes it easy for you to accomplish these things by helping to manage
data in a disconnected mode. The data adapter fills a DataSet object when reading
the data and writes in a single batch when persisting changes back to the database.
A data adapter contains a reference to the connection object and opens and closes
Additionally, the data adapter contains command object references for SELECT,
INSERT, UPDATE, and DELETE operations on the data. You will have a data adapter
defined for each table in a DataSet and it will take care of all communication with
Explorer.
3. Right click on Data Connections and select Create New SQL Server Database.
d. Click OK.
1. Now, Expand your database Right click on Tables Add New Table.
Query:
5. );
3. After finishing table click on Update button that is the upper right corner of
design pane.
4. Right click on Student Table and select Show Table Data. Now, fill some demo
1. Now, your database and tables are ready. You can find your connection string in
a. Right Click on Database Properties. Now, you have a database with a table and a
connection string. The next step is to connect to the database and retrieve the
1. Go to File > New > Project. Create a new console application, FirstProgram and
click OK.
2. Paste the following code in the program window and press ctrl + F5
using System;
1. using System.Data.SqlClient;
2.
4. {
5. class Program
6. {
8. {
Catalog=TestDB;Integrated Security=True";
12. con.Open();
16. {
18. }
19. }
20. }
Output
1 Jack C#
2 Mathew Java
3 Steven C++
1. Go to File New Project. Select Windows Form Application (C#), give project
2. Drag and Drop a Button and a Label Control to Form. You can find these controls
on Tool Box. If Tool Box is not available to open it from View Tool Box
3. Double Click on the Button control. It will open button_click event in code windows.
1. using System;
2. using System.Windows.Forms;
3. using System.Data.SqlClient;
4.
5. namespace FirstForm
8. {
9. public Form1()
10. {
11. InitializeComponent();
12. }
13.
15. {
Catalog=TestDB;User ID=sa;Password=System123;Pooling=False";
19. con.Open();
23. {
+ reader[2].ToString();
25. }
26. }
27. }
28. }
WORKING WITH DB
the connection string and opens a connection. You need to different type of
OLE DB – OleDbConnection
ODBC – OdbcConnection
Oracle – OracleConnection
Connection String combines all the required authentic information that is used for
connecting to a Data Source, like Server Name, Database Name, User Name,
Password etc. It is just a single line string that is used by connection object to
or,
ID=sa;Password=System123;Pooling=False
each and every connection. You can store the connection string
If you are developing ASP.Net Project or ASP Web Project then you can store the
Source=.\SQLEXPRESS;Initial Catalog=StudentDB;Integrated
Security=True;Pooling=False"/>
3. </connectionStrings>
You can access this connection string in ASP.NET MVC, like this
1. using System.Configuration;
2.
3. namespace ConnectionString_Example.Controllers
4. {
6. {
8.
9. {
ConfigurationManager.ConnectionStrings["studentconn"].ToString();
12. }
14. }
If you are working on the windows form, you can save connection string
in App.config file.
1. <connectionStrings>
Source=.\SQLEXPRESS;Initial Catalog=TestDB;User
ID=sa;Password=System123;Pooling=False"/>
3. </connectionStrings>
1. using System;
2. using System.Windows.Forms;
3. using System.Data.SqlClient;
4. using System.Configuration;
5.
6. namespace FirstForm
7. {
11. {
12. InitializeComponent();
13. }
14.
16. {
ConfigurationManager.ConnectionStrings["StudentConn"].ConnectionString;
19. con.Open();
20. }
21. }
22. }
If ConfigurationManager Object does not appear or giving reference error, then you
2. Reference Manager window will appear. Here, Choose Framework in left panel and
CONNECT TO DATASOURCE
3. 3. Open Connection
Example
Catalog=TestDB;User ID=sa;Password=System123;Pooling=False"; );
2. con.Open();
4. con.Close();
The first thing you will need to do when interacting with a database is to create a
connection. The connection tells the rest of the ADO.NET code which database it is
talking to. It manages all of the low-level logic associated with the specific database
protocols. This makes it easy for you because the most work you will have to do in
code instantiates the connection object, open the connection, and then close the
connection when you are done. Because of the way that other classes in ADO.NET
are built, sometimes you don’t even have to do that much work.
Although working with connections is very easy in ADO.NET, you need to understand
connections in order to make the right decisions when coding your data access
stand-alone client application that works on a single database one machine, you
probably don’t care about this. However, think about an enterprise application where
hundreds of users throughout a company are accessing the same database. Each
connection represents overhead and there can only be a finite amount of them. To
look at a more extreme case, consider a Web site that is being hit with hundreds of
thousands of hits a day Applications that grab connections and don’t let them go can
A SqlConnection is an object, just like any other C# object. Most of the time, you
just declare and instantiate the SqlConnection all at the same time, as shown below:
argument of type string. This argument is called a connection string. The table below
specifying how to make a database connection. They include the location, name
Connection String
Description
Parameter Name
Integrated Security is secure when you are on a single machine doing development.
However, you will often want to specify security based on a SQL Server User ID
with permissions set specifically for the application you are using. The following
ID=YourUserID;Password=YourPassword");
Notice how the Data Source is set to DatabaseServer to indicate that you can
identify a database located on a different machine, over a LAN, or over the Internet.
Using a SqlConnection
The purpose of creating a SqlConnection object is so you can enable other ADO.NET
code to work with a database. Other ADO.NET objects, such as a SqlCommand and
We’ve already seen how to instantiate a SqlConnection. The rest of the steps,
using System;
using System.Data;
using System.Data.SqlClient;
/// </summary>
class SqlConnectionDemo
try
conn.Open();
//
rdr = cmd.ExecuteReader();
while (rdr.Read())
Console.WriteLine(rdr[0]);
finally
if (rdr != null)
rdr.Close();
if (conn != null)
conn.Close();
the SqlConnection instance, conn. Any operations on a connection that was not yet
opened will generate an exception. So, you must open the connection before using it.
Before using a SqlCommand, you must let the ADO.NET code know which connection
the SqlConnection object, conn. Any operations performed with the SqlCommand will
The code that uses the connection is a SqlCommand object, which performs a query
the while loop reads the first column from each row of the result set, which is the
CustomerID column. Right now, it is important for you to understand that these
objects are using the SqlConnection object so they know what database to interact
with.
When you are done using the connection object, you must close it. Failure to do so
application. There are a couple points to be made about how we closed the connection
Notice that we wrapped the ADO.NET code in a try/finally block. The finally blocks
help guarantee that a certain piece of code will be executed, regardless of whether
you will want to make sure they are closed in finally blocks.
Another precaution you should take when closing connections is to make sure the
connection object is not null. If something goes wrong when instantiating the
connection, it will be null and you want to make sure you don’t try to close an invalid
You have seen how to use a SqlConnection object with a SqlDataReader, which
required explicitly closing the connection. However, when using a disconnected data
model, you don’t have to open and close the connection yourself.
The keyword INSERT INTO is used for inserting records in a table. There are 2
This is the easiest way to insert records into a table but I strongly avoid it because
or,
Programming Example
1. using System;
2. using System.Data.SqlClient;
3.
4. namespace InsertRecords
5. {
6. class Program
7. {
9. {
13. try
14. {
15. con.Open();
16. cmd.ExecuteNonQuery();
18. }
20. {
22. }
23. finally
24. {
25. con.Close();
26. Console.ReadKey();
27. }
28. }
29. }
30. }
PARAMETERIZED QUERY
We always prefer to use Parameterized Query over simple SQL Query because it
prevents SQL Injection Attacks. Here is programming example in which you can learn
Programming Example
1. using System;
2. using System.Data.SqlClient;
3.
4. namespace InsertRecords
5. {
6. class Program
7. {
9. {
12. string query = "INSERT INTO Products (Name, Price, Date) VALUES(@Na
14.
19.
20. try
21. {
22. con.Open();
23. cmd.ExecuteNonQuery();
25. }
27. {
29. }
30. finally
31. {
32. con.Close();
33. Console.ReadKey();
34. }
35. }
37. }
Output
A Store Procedure is a Pre Compiled SQL Queries that is saved into server. The
Benefit of Store Procedure is you don't need to write same SQL Queries again and
again. Store Procedure get compiled once and can be used forever. However, it is
easy to create store procedure in SQL Server Management Studio but here I will
explain how you can create and execute Store Procedure right from your program.
2. (
3. @Name VARCHAR(50),
4. @Price VARCHAR(50),
5. @Date DATETIME
6. )
7. AS
You can create this store procedure in Server Explorer or SQL Server Management
1. using System;
2. using System.Data.SqlClient;
3.
4. namespace Create_Store_Procedure
5. {
6. class Program
7. {
12. @"
14. (
18. )
19. AS
21. ";
22.
24. try
25. {
26. con.Open();
27. cmd.ExecuteNonQuery();
29. }
31. {
34. finally
35. {
36. con.Close();
37. Console.ReadKey();
38. }
39. }
40. }
41. }
1. using System;
2. using System.Data.SqlClient;
3. using System.Data;
4.
5. namespace Create_Store_Procedure
6. {
7. class Program
8. {
10. {
14. {
15. con.Open();
21. if(i>0)
22. {
24. }
25.
26. }
28. {
30. }
31. finally
32. {
33. con.Close();
34. Console.ReadKey();
35. }
36. }
37. }
Output:
Here, you need to create one more Store Procedure to retrieve records from
database table.
2. (
3. @Name VARCHAR(50)
4. )
5. AS
Programming Example
1. using System;
2. using System.Data.SqlClient;
3. using System.Data;
4.
5. namespace Create_Store_Procedure
6. {
7. class Program
8. {
12. try
13. {
14. con.Open();
19. while(dr.Read())
20. {
24. }
25.
26. }
28. {
30. }
31. finally
32. {
33. con.Close();
34. Console.ReadKey();
36. }
37. }
38. }
Output
DATAREADER ADO.NET
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
A SqlDataReader is a type that is good for reading data in the most efficient manner
possible. You can *not* use it for writing data. SqlDataReaders are often described
You can read from SqlDataReader objects in a forward-only sequential manner. Once
you’ve read some data, you must save it because you will not be able to go back and
read it again.
doesn’t have the overhead associated with traversing the data or writing it back to
the data source. Therefore, if your only requirement for a group of data is for
the best choice. Also, if the amount of data you need to read is larger than what you
would prefer to hold in memory beyond a single call, then the streaming behavior of
When you want to only display information or search result, you can use DataReader.
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
2. By default DataReader stores only one row at a time in memory. It reduces system
overhead.
Properties
PROPERTY DESCRIPTION
Methods
METHOD DESCRIPTION
anything for you. As you learned in previous lessons, the SqlCommand object
references the connection and the SQL statement necessary for the SqlDataReader
to obtain data.
previous lessons contained code that used a SqlDataReader, but the discussion was
delayed so we could focus on the specific subject of that particular lesson. This
lesson builds from what you’ve seen and explains how to use the SqlDataReader.
read this data, you must pull data from a table row-by-row Once a row has been read,
the previous row is no longer available. To read that row again, you would have to
create a new instance of the SqlDataReader and read through the data stream again.
The typical method of reading from the data stream returned by the SqlDataReader
is to iterate through each row with a while loop. The following code shows how to
accomplish this:
while (rdr.Read())
Console.Write("{0,-25}", contact);
Console.Write("{0,-25}", company);
Console.WriteLine();
Notice the call to Read on the SqlDataReader, rdr, in the while loop condition in the
code above. The return value of Read is type bool and returns true as long as there
are more records to read. After the last record in the data stream has been
In previous lessons, we extracted the first column from the row by using the
SqlDataReader indexer, i.e. rdr[0]. You can extract each column of the row with a
numeric indexer like this, but it isn’t very readable. The example above uses a string
indexer, where the string is the column name from the SQL query (the table column
name if you used an asterisk, *. String indexers are much more readable, making the
return type object. This is why the example above casts results to a string. Once
the values are extracted, you can do whatever you want with them, such as printing
Always remember to close your SqlDataReader, just like you need to close the
SqlConnection. Wrap the data access code in a try block and put the close
finally
if (rdr != null)
rdr.Close();
The code above checks the SqlDataReader to make sure it isn’t null. After the
code knows that a good instance of the SqlDataReader exists, it can close it.
Listing 1 shows the code for the previous sections in its entirety.
using System;
using System.Data;
using System.Data.SqlClient;
namespace Lesson04
class ReaderDemo
rd.SimpleRead();
try
conn.Open();
rdr = cmd.ExecuteReader();
Console.WriteLine(
Console.WriteLine(
record
while (rdr.Read())
Console.Write("{0,-25}", contact);
Console.Write("{0,-25}", company);
Console.WriteLine();
finally
if (rdr != null)
rdr.Close();
if (conn != null)
conn.Close();
There are dozens of Getxxx methods. These methods read a specific data
type value from a column. For example. GetChar will return a column value as a
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
A DataSet behaves like real Database and it represents a complete set of data that
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.
A DataSet is an in-memory data store that can hold numerous tables. DataSets only
hold data and do not interact with a data source. It is the SqlDataAdapter that
manages connections with the data source and gives us disconnected behavior. The
SqlDataAdapter opens a connection only when required and closes it as soon as it has
performed its task. For example, the SqlDataAdapter performs the following tasks
1. Open connection
3. Close connection
1. Open connection
3. Close connection
you are free to read and write data with the DataSet as you need. These are the
A couple scenarios illustrate why you would want to work with disconnected data:
people working without network connectivity and making Web sites more scalable.
Consider salespeople who need customer data as they travel. At the beginning of the
day, they’ll need to sync up with the main database to have the latest information
available. During the day, they’ll make modifications to existing customer data, add
new customers, and input new orders. This is okay because they have a given region
or customer base where other people won’t be changing the same records. At the
end of the day, the salesperson will connect to the network and update changes for
overnight processing.
Another scenario is making a Web site more scalable. With a SqlDataReader, you
have to go back to the database for records every time you show a page. This
requires a new connection for each page load, which will hurt scalability as the
number of users increases. One way to relieve this is to use a DataSet that is
updated one time and stored in the cache. Every request for the page checks the
cache and loads the data if it isn’t there or just pulls the data out of the cache and
displays it. This avoids a trip to the database, making your application more efficient.
Exceptions to the scenario above include situations where you need to update data.
You then have to make a decision, based on the nature of how the data will be used
as to your strategy. Use disconnected data when your information is primarily read-
only, but consider other alternatives (such as using a SqlCommand object for
immediate update) when your requirements call for something more dynamic. Also, if
to use SqlDataReader for read-only data. Really, one could come up with all kinds of
exceptions, but the true guiding force should be the requirements of your application
There isn’t anything special about instantiating a DataSet. You just create a new
overload that accepts a string for the name of the DataSet, which is used if you
were to serialize the data to XML. Since that isn’t a requirement for this example,
I left it out. Right now, the DataSet is empty and you need a SqlDataAdapter to load
it.
WHAT IS DATAADAPTERS?
Source and then Fill Data to DataSets. It also Updates Data Source with DataSets.
Properties:
Properties Description
Methods:
Method Description
Creating A SqlDataAdapter
The SqlDataAdapter holds the SQL commands and connection object for reading
and writing data. You initialize it with a SQL select statement and connection object:
The code above creates a new SqlDataAdapter, daCustomers. The SQL select
statement specifies what data will be read into a DataSet. The connection
object, conn, should have already been instantiated, but not opened. It is the
interact with the data source. The code showed how to specify the select statement,
but didn’t show the insert, update, and delete statements. These are added to the
There are two ways to add insert, update, and delete commands: via SqlDataAdapter
properties or with a SqlCommandBuilder. We are going to see the easy way of doing
it with the SqlCommandBuilder. In a later lesson, we will also see how to use the
SqlDataAdapter properties, which takes more work but will give you more
capabilities than what the SqlCommandBuilder does. Here’s how to add commands to
Notice in the code above that the SqlCommandBuilder is instantiated with a single
SqlCommandBuilder will read the SQL select statement (specified when the
SqlDataAdapter was instantiated), infer the insert, update, and delete commands,
and assign the new commands to the Insert, Update, and Delete properties of the
SqlDataAdapter, respectively.
do a simple select statement on a single table. However, when you need a join of two
Once you have a DataSet and SqlDataAdapter instances, you need to fill the
DataSet. Here’s how to do it, by using the Fill method of the SqlDataAdapter:
daCustomers.Fill(dsCustomers, "Customers");
The Fill method, in the code above, takes two parameters: a DataSet and a table
name. The DataSet must be instantiated before trying to fill it with data. The second
parameter is the name of the table that will be created in the DataSet. You can name
the table anything you want. Its purpose is so you can identify the table with a
meaningful name later on. Typically, I’ll give it the same name as the database table.
However, if the SqlDataAdapter’s select command contains a join, you’ll need to find
The Fill method has an overload that accepts one parameter for the DataSet only.
In that case, the table created has a default name of “table1” for the first table.
The number will be incremented (table2, table3, …, tableN) for each table added to
the DataSet where the table name was not specified in the Fill method.
A DataSet will bind with both ASP.NET and Windows forms DataGrids. Here’s an
dgCustomers.DataSource = dsCustomers;
dgCustomers.DataMember = "Customers";
The first thing we do, in the code above, is assigned the DataSet to the DataSource
property of the DataGrid. This lets the DataGrid know that it has something to bind
to, but you will get a ‘+’ sign in the GUI because the DataSet can hold multiple tables
table to use, set the DataGrid’s DataMember property to the name of the table. In
the example, we set the name to Customers, which is the same name used as the
second parameter to the SqlDataAdapter Fill method. This is why I like to give the
table a name in the Fill method, as it makes the subsequent code more readable.
Updating Changes
After modifications are made to the data, you’ll want to write the changes back to
the database. Refer to the previous discussion in the Introduction of this chapter
on update guidance. The following code shows how to use the Update method of the
daCustomers.Update(dsCustomers, "Customers");
The Update method, above, is called on the SqlDataAdapter instance that originally
filled the dsCustomers DataSet. The second parameter to the Update method
specifies which table, from the DataSet, to update. The table contains a list of
records that have been modified and the Insert, Update, and Delete properties of
modifications.
using System;
1. using System.Data.SqlClient;
2. using System.Data;
3.
5. {
6. class Program
7. {
9. {
Catalog=ComputerShop;Integrated Security=True";
ConString);
15. Console.WriteLine(ds.GetXml());
16. Console.ReadKey();
17. }
18. }
19. }
Output
1.
3. 1
4. LED Screen
5. $120
6. 2017-01-27T00:00:00+05:30
7.
8.
9. 2
11. $20
12. 2017-05-25T00:00:00+05:30
13.
14.
2. using System.Data;
3. using System.Data.SqlClient;
4. using System.Windows.Forms;
5. namespace DataSet_Exampl
6. {
8. {
9. public Form1()
10. {
11. InitializeComponent();
12. }
13.
15. {
Catalog=ComputerShop;Integrated Security=True";
18.
21.
24. }
25. }
26. }
Output
After populating dataset, you can update, insert or delete a record from the dataset.
2. {
3. //Fill Dataset
Catalog=ComputerShop;Integrated Security=True";
8. adapter.Fill(set, "Items");
9.
15. set.Tables["Items"].Rows.Add(row);
16.
18. }
If you don’t know row index or unique row number still you can update or edit row in
2. {
3. //Fill Dataset
Catalog=ComputerShop;Integrated Security=True";
8. adapter.Fill(set, "Items");
9.
11.
13. }
Output
3. //Fill Dataset
Catalog=ComputerShop;Integrated Security=True";
8. adapter.Fill(set, "Items");
9.
10. set.Tables["Items"].Rows[1].Delete();
11.
13. }
Output
Programming Example
2. {
3. //Fill Dataset
Catalog=ComputerShop;Integrated Security=True";
8. adapter.Fill(set, "Items");
9.
15. set.Tables["Items"].Rows.Add(row);
16.
19. adapter.Update(set.Tables["Items"]);
20.
22.
23. }
Output
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.
2. {
Integrated Security=True";
5.
8.
9. adapter.Fill(set, "Items");
12. }
2. {
Integrated Security=True";
5.
8.
9. adapter.Fill(set, "Items");
13. newRow.BeginEdit();
17. newRow.EndEdit();
19. }
2. {
Integrated Security=True";
5.
8.
9. adapter.Fill(set, "Items");
12. dv[1].BeginEdit();
15. dv[1].EndEdit();
16.
18. }
Output
2. {
Integrated Security=True";
5.
8.
9. adapter.Fill(set, "Items");
12. dv.Table.Rows[2].Delete();
13.
15. }
Output