Ado Net
Ado Net
NET
ADO.NET is a module of .Net Framework which is used to establish connection between application and data
sources. Data sources can be such as SQL Server and XML. ADO.NET consists of classes that can be used to
connect, retrieve, insert and delete data.
All the ADO.NET classes are located into System.Data.dll and integrated with XML classes located into
System.Xml.dll.
These are the components that are designed for data manipulation and fast access to data. Those are used to
perform database operations.
is used to connect to the database, execute commands and retrieve the record. It is lightweight component with
better performance.
1. Connection
2. Command
3. DataReader
4. DataAdapter
SqlConnection
It is used to establish an open connection to the SQL Server database. It is a sealed class so that cannot be
inherited. SqlConnection class uses SqlDataAdapter and SqlCommand classes together to increase performance
when connecting to a Microsoft SQL Server database
Syntax:
SqlCommand
This class is used to store and execute SQL statement for SQL Server database. It is a sealed class so that cannot be
inherited.
Initilization:
It is a connected architecture, which means when you require data from the database you need to connect with
database and fetch the data from there. You can use if you need read data from the database in a faster manner.
DataReader is Read/Forward only that means we can only get the data using this but we cannot update or insert
the data into the database. It fetches the record one by one.
Initilization:
DataSet
It is a type of disconnected architecture. Disconnected architecture means, you don’t need to connect always
when you want to get data from the database. You can get data from dataset; basically DataSet is a collection of
datatables. We can store the database table, view data in the DataSet. It is an in-memory data store that can hold
more than one table at the same time
Initilization:
DataSet();
Object Creation:
DataAdapter
The DataAdapter works as a bridge between a DataSet and a data source to retrieve data. DataAdapter is a class
that represents a set of SQL commands and a database connection. It can be used to fill the DataSet and update
the data source.
Initilization:
DataTable
DataTable is defined as the class which contains a number of rows and columns for to storing and retrieving the
data's from both the memory and the database. A DataSet is made up of a collection of tables, relationships, and
constraints. In ADO.NET, DataTable objects are used to represent the tables in a DataSet. A DataTable represents
one table of in-memory relational data;
Initilization:
DataTable();
Object Creation:
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=TestDB; integrated
security=true");
// writing sql query
SqlCommand cm = new SqlCommand
("create table student(id int not null, name varchar(100), email
varchar(50))", con);
// Opening Connection
con.Open();
// Executing the SQL query
cm.ExecuteNonQuery();
// Displaying a message
Console.WriteLine("Table created Successfully");
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong." + e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}
Insert:
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=TestDB; integrated
security= true");
// writing sql query
SqlCommand cm = new SqlCommand("insert into student (id, name,
email)values('101', 'Ronald Trump', '[email protected]')", con);
// Opening Connection
con.Open();
// Executing the SQL query
var data = cm.ExecuteNonQuery();
// Displaying a message
Console.WriteLine("Record Inserted Successfully");
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong." + e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}
Retrieve:
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=TestDB; integrated
security=true");
// writing sql query
SqlCommand cm = new SqlCommand("Select * from student", con);
// Opening Connection
con.Open();
// Executing the SQL query
SqlDataReader sdr = cm.ExecuteReader();
// Iterating Data
while (sdr.Read())
{
Console.WriteLine(sdr["id"] + " " + sdr["name"] + " " +
sdr["email"]); // Displaying Record
}
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong.\n" + e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}
Update:
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=TestDB; integrated
security=true");
// writing sql query
SqlCommand cm = new SqlCommand("update student set name='kiran' where id
= '101'", con);
// Opening Connection
con.Open();
// Executing the SQL query
cm.ExecuteNonQuery();
Console.WriteLine("Record Updated Successfully");
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong.\n" + e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}
Deletion:
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=TestDB; integrated security=true");
// writing sql query
SqlCommand cm = new SqlCommand("delete from student where id = '101'", con);
// Opening Connection
con.Open();
// Executing the SQL query
cm.ExecuteNonQuery();
Console.WriteLine("Record Deleted Successfully");
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong.\n" + e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}
Dataset Example:
using System;
using System.Data;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
class Program
program.InsertUserInput();
con.Open();
dataadpat.Fill(ds);
}}}}}
Data Table Example:
using System;
using System.Data;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
class Program
try
{
Id.DataType = typeof(int);
Id.Unique = true;
Id.AllowDBNull = false;
dataTable.Columns.Add(Id);
Name.MaxLength = 50;
Name.AllowDBNull = false;
dataTable.Columns.Add(Name);
row1["Id"] = 101;
row1["Name"] = "Anurag";
row1["Email"] = "[email protected]";
dataTable.Rows.Add(row1);
}
}
catch (Exception e)
Console.ReadKey();
}
Important Methods of Dataset in C#:
Copy(): Copies both the structure and data of the DataSet. That means it returns a new DataSet with the
same structure (table schemas, relations, and constraints) and data as the original DataSet.
Clone(): Copies the structure of the DataSet, including all schemas, relations, and constraints. But does
not copy any data. That means it returns a new DataSet with the same schema as the current DataSet but
without the data.
Clear(): Clears the DataSet of any data by removing all rows in all tables.
Remove(DataTable table): This method removes the specified DataTable object from the collection.
Example:
using System;
using System.Data;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
class Program
{
try
{
string ConnectionString = @"data source=; database=TestDB; integrated security=true";
da.Fill(originalDataSet);
}
Console.WriteLine();
if (copyDataSet.Tables != null)
}
Console.WriteLine();
if (cloneDataSet.Tables[0].Rows.Count > 0)
else
{
Console.WriteLine("Clone Data Set is Empty");
Console.WriteLine();
//Clears the DataSet of any data by removing all rows in all tables.
copyDataSet.Clear();
if (copyDataSet.Tables[0].Rows.Count > 0)
{
}
}
else
removeDataSet.Tables[0].TableName = "Student";
removeDataSet.Tables[1].TableName = "veda";
removeDataSet.Tables.Remove(removeDataSet.Tables["Student"]);
}
}
Console.ReadKey();
}
}
------------------------------------------------------------------------------------------------------------------------------------------
What are the different execute() methods available in ADO.NET?
ExecuteScalar(): This method returns only a single value from the first row and first column of the
ResultSet after the execution of the query. Even if ResultSet is having more than one row or column, all
those rows and columns will be ignored. If the ResultSet is empty, it will return NULL.
ExecuteNonQuery(): This method returns the number of rows affected by the execution of a query.
This method is not useful to return the ResultSet.
ExecuteReader(): This method returns an object of DataReader which is a read-only and forward-
only ResultSet. It needs a live connection with the Data Source. We cannot directly instantiate the
DataReader object. A valid DataReader object can be created with the help of the ExecuteReader()
method.
ExecuteXmlReader(): This method builds an object of the XmlReader class and will return the ResultSet
in the form of an XML document. This method is made available in SQL Server 2000 or later
Store Procedure Example:
using System;
using System.Data;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=TestDB; integrated
security=true");
// writing sql query
SqlCommand cm = new SqlCommand("Proc_GetDatawithParam", con);
cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue("@name", "kiran");
// Opening Connection
con.Open();
// Executing the SQL query
SqlDataReader sdr = cm.ExecuteReader();
// Iterating Data
while (sdr.Read())
{
Console.WriteLine(sdr["id"] + " " + sdr["name"] + " " +
sdr["email"]); // Displaying Record
}
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong.\n" + e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}