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

Ado Net

ADONET TEXT BOOK
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Ado Net

ADONET TEXT BOOK
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

ADO.

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.

.NET Framework Data Providers

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:

SqlConnection _Con = new SqlConnection("Data Source= (local)/server; Initial Catalog/database=


EmployeeDataBase; User ID=User Name; pwd=User Password" Integrated Security=”True”/”false”);

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:

SqlCommand cm = new SqlCommand(String(your query), SqlConnection)


DataReader

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:

SqlDataReader sdr = command.ExecuteReader();

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:

DataSet ds = new DataSet();

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:

SqlDataAdapter sde = new SqlDataAdapter(String, SqlConnection);

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:

DataTable table = new DataTable();


Example on Table 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

static void Main(string[] args)

Program program = new Program();

program.InsertUserInput();

public void InsertUserInput()

using (SqlConnection con = new SqlConnection

("data source=.; database=TestDB; integrated security=true"))

con.Open();

SqlDataAdapter dataadpat = new SqlDataAdapter

("Select * from student;Select * from veda", con);

DataSet ds = new DataSet();

dataadpat.Fill(ds);

var tablescount = ds.Tables.Count;

for (int i = 0; i < ds.Tables.Count; i++)

foreach (DataRow sdr in ds.Tables[i].Rows)

Console.WriteLine(sdr["id"] + " " + sdr["name"] + " " + sdr["email"]);

}}}}}
Data Table Example:
using System;

using System.Data;
using System.Data.SqlClient;

namespace AdoNetConsoleApplication

class Program

static void Main(string[] args)

try
{

//Creating data table instance


DataTable dataTable = new DataTable("Teacher");

//Add the DataColumn using all properties

DataColumn Id = new DataColumn("ID");

Id.DataType = typeof(int);

Id.Unique = true;

Id.AllowDBNull = false;
dataTable.Columns.Add(Id);

//Add the DataColumn few properties

DataColumn Name = new DataColumn("Name");

Name.MaxLength = 50;

Name.AllowDBNull = false;

dataTable.Columns.Add(Name);

//Add the DataColumn using defaults


DataColumn Email = new DataColumn("Email");
dataTable.Columns.Add(Email);

//Setting the Primary Key

dataTable.PrimaryKey = new DataColumn[] { Id };

//Add New DataRow by creating the DataRow object

DataRow row1 = dataTable.NewRow();

row1["Id"] = 101;

row1["Name"] = "Anurag";

row1["Email"] = "[email protected]";
dataTable.Rows.Add(row1);

//Adding new DataRow by simply adding the values

dataTable.Rows.Add(102, "Mohanty", "[email protected]");

foreach (DataRow row in dataTable.Rows)

Console.WriteLine(row["Id"] + ", " + row["Name"] + ", " + row["Email"]);

}
}

catch (Exception e)

Console.WriteLine("OOPs, something went wrong.\n" + 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

static void Main(string[] args)

{
try

{
string ConnectionString = @"data source=; database=TestDB; integrated security=true";

using (SqlConnection connection = new SqlConnection(ConnectionString))

SqlDataAdapter da = new SqlDataAdapter("select * from student;select * from veda",


connection);

DataSet originalDataSet = new DataSet();

da.Fill(originalDataSet);

Console.WriteLine("Original Data Set:");

foreach (DataRow row in originalDataSet.Tables[0].Rows)


{
Console.WriteLine(row["Name"] + ", " + row["Email"] + ", " + row["id"]);

}
Console.WriteLine();

Console.WriteLine("Copy Data Set:");

//Copies both the structure and data for this System.Data.DataSet.

DataSet copyDataSet = originalDataSet.Copy();

if (copyDataSet.Tables != null)

foreach (DataRow row in copyDataSet.Tables[0].Rows)


{

Console.WriteLine(row["Name"] + ", " + row["Email"] + ", " + row["id"]);


}

}
Console.WriteLine();

Console.WriteLine("Clone Data Set");

// Copies the structure of the DataSet, including all DataTable

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


DataSet cloneDataSet = originalDataSet.Clone();

if (cloneDataSet.Tables[0].Rows.Count > 0)

foreach (DataRow row in cloneDataSet.Tables[0].Rows)

Console.WriteLine(row["Name"] + ", " + row["Email"] + ", " + row["id"]);

else
{
Console.WriteLine("Clone Data Set is Empty");

Console.WriteLine("Adding Data to Clone Data Set Table");


cloneDataSet.Tables[0].Rows.Add(101, "Test1", "[email protected]");

cloneDataSet.Tables[0].Rows.Add(101, "Test2", "[email protected]");

foreach (DataRow row in cloneDataSet.Tables[0].Rows)

Console.WriteLine(row["Name"] + ", " + row["Email"] + ", " + row["id"]);

Console.WriteLine();

//Clears the DataSet of any data by removing all rows in all tables.
copyDataSet.Clear();

if (copyDataSet.Tables[0].Rows.Count > 0)
{

foreach (DataRow row in copyDataSet.Tables[0].Rows)

Console.WriteLine(row["Name"] + ", " + row["Email"] + ", " + row["id"]);

}
}

else

Console.WriteLine("After Clear No Data is Their...");

// remove required table in table list

DataSet removeDataSet = originalDataSet.Copy();

removeDataSet.Tables[0].TableName = "Student";

removeDataSet.Tables[1].TableName = "veda";
removeDataSet.Tables.Remove(removeDataSet.Tables["Student"]);

}
}

catch (Exception ex)

Console.WriteLine($"Exception Occurred: {ex.Message}");

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.Add(new SqlParameter("@name", "kiran"));

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();
}
}
}
}

You might also like