Unit-3 ADO - Net Updated
Unit-3 ADO - Net Updated
ADO.NET
Outline
SQL & SQL Syntax
Benefits of ADO.NET
Difference between ADO.NET and Classical ADO
Database connectivity Namespace
ADO.NET Architecture
Managed Data Provider
DataSet
Connection & Command Object
Data Adapter Class
DataSet Class
DataView Class
ADO.NET Example
Connected & Disconnected Mode
Data Binding
SQL
• Full form of the SQL is structure query language.
• Structure Query Language (SQL) is the language used to manipulate
relational database.
• SQL is tied very closely with the relational model.
Syntax :
• Select * from TableName; //For all rows and columns
• Select ColumnName from TableName; //For specific column
• Select * from TableName where <condition> //For Particular criteria
• Select * from TableName Order by ColumnName //Order wise
Example :
• Select * from emp;
• Select Ename , Empno from emp;
• Select * from emp where Empno = 1;
• Select Ename , Empno from emp Order by Ename;
SQL Syntax
2. Insert :
• Creates a new row and inserts values into specified columns.
Syntax :
• Insert into TableName values (Value1 , Value2 , ….)
Example :
• Insert into Cat values (1 , ‘Nokia’);
SQL Syntax
3. Update :
• Changes the values of individual columns in one or more existing rows in a
table.
Syntax :
• Update TableName set columnname = value // For all
• Update Tablename set columnname = value where columnname = value
// For particular row
Example :
• Update Emp set dal = 1000000;
• Update Product set Pname = ‘NokiaNseries’ , Amt = 5000 where ProductId
= 10;
SQL Syntax
4. Delete :
• Removes one or more rows from a table.
Syntax :
• Delete from TableName; // Delete all rows
• Delete from Tablename where columnName = value; // Delete
particular row
Example :
• Delete from product;
• Delete from stu where id = 11;
SQL Syntax
5. Aggregate Function :
• Aggregate functions always return one value.
• There are 5 aggregate function : MAX, MIN, SUM, AVG, COUNT
Syntax :
• Select AggregateFunName (Columnname) from TableName;
Example :
• Select Max (sal) from Emp;
• Select Min (sal) from Emp;
• Select Sum (sal) from Emp;
• Select Avg (sal) from Emp;
• Select Count (empno) from Emp;
ADO.NET
• Most applications require some form of data access.
• ADO.NET is a part of the Microsoft .NET Framework.
• The full form of ADO.NET is ActiveX Data Objects.
• ADO.NET has the ability to separate data access mechanism, data
manipulation mechanism and data connectivity mechanism.
• ADO.NET is a set of classes that allows applications to read and write
information in databases.
2. Maintainability :
• When you replace a single tier with two tiers or two tiers with three tiers,
arrange for those tiers to trade information. If the original application is
implemented in ADO.NET using datasets, this transformation is made
easier.
3. Performance :
• ADO.NET provides fast execution of data over ADO model.
Benefits of ADO.NET
4. Programmability :
• ADO.NET provides a very rich API which helps developers to develop
programs more quickly and with fewer mistakes. Typed DataSet provides
safe data and it checks compile time.
5. Scalability :
• ADO.NET provides disconnected mode so there is no problem of
scalability and unlike ADO.NET does not support database locking
concept.
Benefits of ADO.NET
6. Disconnected :
• In connected mode, we make a connection to the Database server and then
interact with it.
• The application stays connected to the Database server even when it is not
using Database services. It is wastes database resource.
• ADO.NET supports disconnected environment it solves this problem by
managing a local buffer of persistent data called DataSet.
• Application automatically connects to the server when it need to pass some
query and then disconnects immediately after getting the result back and
storing it in dataset.
Compare ADO.NET to Classic ADO
Difference ADO ADO.NET
Data Access Connection Model Disconnected model
Locking Supports Does not support
XML Support Limited Robust
Format of Data Transferring COM based XML for transferring data
to and from your database
and web application.
Data Provide Record Set DataSet and Data Adapter
Data Persistent Stores the data in the XML Stores the data in the
format. binary format.
Tables Record set, is like a single Data Set can contain
table or query result. multiple tables.
Cursor Supports Does not support
Connection Client application need to Client disconnected as
be connected to data soon as the data is fetched
server while working on or processed.
data.
Database Connectivity Namespaces
1. System.Data :
• It provides database independent classes and DataSet, DataTable,
DataRow, DataColumn and DataRelation Classes.
2. System.Data.Common :
• It provides data provider classes such as System.Data.SqlClient,
System.Data.Oledb, System.Data.OracleClient etc..
5. System.Data.OracleClient :
• It is collection of classes such as OracleConnection, OracleCommand,
OracleDataReader, etc.. It use when backend data as Oracle.
6. System.Data.SqlTypes :
• Provide classes that are SQL server specific data types such as SqlBinary,
SqlBoolean, SqlByte, SqlChar, SqlDateTime, SqlDecimal, SqlFileStream,
SqlInt16, SqlInt64, SqlMoney, SqlSingle, SqlString, SqlXml.
Database Connectivity Ways
Connected :
• Client uses data from Database directly not from Dataset so Database
connectivity is upto client closes form.
Fetch
Data
Command
Reader
Data Connection
Return Data
Application
DataBase
Database Connectivity Ways
Disconnected :
• Data stored into Dataset and client uses data from Dataset only so Database
connectivity for fraction of minute.
Data Adapter
Fill Data
Database
Disconnected Data Access Connected Data Access
ADO.NET Architecture
Data Set
Connection
Data Table Collection
Transaction Data Adapter
Data Table
Select Command
Data Row Collection
Command
Insert Command
Data Row Collection
Parameters
Update Command
Data Row Collection
Delete Command
Data Reader
Data Relation Collection
Database XML
ADO.NET Architecture
• There are two major components of ADO.NET.
ADO.NET
ADO.NET Architecture
Data Set :
• Data Set represents either an entire database or a subset of database. It can
contain tables and relationship between those tables.
Data Provider :
• Data Provider is a collection of components like Connection, Command,
DataReader, DataAdapter objects and handles communication with a
physical data store and the database.
Managed Data Provider
• The Data Provider is responsible for providing and maintaining the
connection to the database.
• It is a set of classes that can be used for communicating with database, and
holding / manipulating data.
• The Data provider connects to the data source on behalf of ADO.NET.
• The data source can be Microsoft SQL server or Oracle database and
OLEDB data provider.
• The Data provider components are specific to data source.
• The data provider consists of the following four objects :
1. Connection
2. Command
3. Data Reader
4. Data Adapter
Managed Data Provider
1. Connection :
• It establishes or connects a connection to the data source.
• The base class of all connection object is DbConnection class.
• The Connection object has the methods for opening and closing connection
and beginning a transaction.
• The Connection object has the properties for setting the timeout property
period of connection.
• The .NET Framework provides four types of Connection classes, namely
SqlConnection, OleDbConnection, OdbcConnection, and
OracleConnection.
• These are designed specifically to connect to provide connections to a wide
range of database, such as MS-Excel and Oracle.
Managed Data Provider
2. Command :
• It fires SQL commands or perform some action on the data source, such as
insert, update and delete.
• Execute a command against the data source and retrieve a DataReader or
Dataset.
• The base class for all command object is the DbCommand class.
• The command object is represented by two classes : SqlCommand and
OleDbCommand
• The ExecuteQuery() method executes the command, such as INSERT,
UPDATE or DELETE that have no return value.
• The ExecuteScalar() method return a single value from a database query.
• The ExecuteReader() method returns a result set through the DataReader
object.
Managed Data Provider
3. Data Reader :
• Used when large list of results one record at time. It reads records in a
read-only forward-only methods.
• The base class of all DataReader objects is the DbDataReader class.
• The DataReader object cannot be directly instantiated.
Managed Data Provider
4. Data Adapter :
• It’s a bridge between DataSource and DataSet object for transferring data.
• Update the Dataset with data from the data source.
• The base class for all the DataAdapter objects is the DbDataAdapter
class.
• It used to fill a DataTable or Dataset with data from database using Fill()
method.
• The DataAdapter object commits the changes to the database by calling the
Update() method.
• It also provides four properties that represent the database command, that
is SelectCommand, InsertCommand, DeleteCommand and
UpdateCommand.
ADO.NET Data Provider
For SQL Imports System.Data.SqlClient namespaces.
Server It provides data access for Microsoft SQL Server.
Example :
DataView dv = new DataView();
dv.RowFilter = “Rno = ” + textBox1.Text;
dv.Sort = “Ename Desc”;
MessageBox.Show ( dv.Count.ToString() );
Data Set / Other ADO.NET Objects
2. Data Table Object :
• Data Set contains Data Table.
• A Data Table object represents a database table.
• It is a collection of Columns and Rows. It is a part of Data Set.
• Data Table represents a single table.
Example :
ds.Tables[“Emp”]
ds.Table[0]
ds.Tables[0].Rows.Count
ds.Tables[0].Columns.Count
Data Set / Other ADO.NET Objects
3. Constraint Object :
• A constraint means rules and regulation.
• It is used to maintain the integrity of the data in the Data Table.
• A constraint class have three types of constraints :
1. Unique key constraint
2. Foreign key constraint
3. Primary key constraint
• The difference between unique and primary key constraints is unique
allows null and primary does not.
• Foreign key constraints dives surety about changes in master table affects
child table.
Data Set / Other ADO.NET Objects
4. DataRelation Object :
• It represents parent child relationship.
• We can create parent child data relations between Data Table using
DataRelation Object.
• Represents a parent / child relationship between two Data Table objects.
• ADO.NET Data Table object maintains a collection of Constraints.
• Each record is identified by matrix form row X column.
Data Set / Other ADO.NET Objects
5. DataRow Object :
• It represents row of the table.
• The Rows property of the DataTable object represents the
DataRowCollection, which is a collection of DataRow objects in a Data
Table.
• Each Data Row object represent a single record in a table that has been
retrieved from the data source.
6. DataColumn Object :
• It represents column of the Table.
• The Column property of the Data Table object represents the
DataColumnCollection, which is a collection of DataColumn objects in a
DataTable.
Connection Object
• The Connection object creates the connection to the database.
• The connection object represents the physical connection to a data source.
• The Connection object contains all of the information required to open a
connection to the database.
Basic Steps :
1. Create Database
2. Create connection object
3. Set the Provider
4. Specify the data source
ConnectionString Property
• A connection string has a group of semi-colon separated attributes.
• Every .NET Data Provider connection string looks different; depending on
the type of .NET Data Provider you need to use and which attributes are
set for each different type of database system.
Keyword Description
Data Source Server Name or network address of SQL Server
AttachDbFilename Name of the database
Integrated Security Whether the connection is a secure Connection
Methods of Connection Object
1. Open :
• It opens the connection to our database.
2. Close :
• It closes the database connection.
3. Dispose :
• It release the resources on the connection object.
4. State :
• Returns 0 for not connected or 1 for connected.
• Return state of connection object.
Command Object
• It’s depends on Connection object.
• Command objects are used to execute commands to a database across a
data connection.
• The Command Object in ADO.NET executes SQL statements and Stored
Procedures against the data source specified in the Connection Object.
• Command objects can support SQL statements and stored procedures that
can return single values; one or more sets of rows or no values at all.
• The Command Object has a property called CommandText, which contains
a String (Query) value that represents the command that will be executed
in the Data Source.
Properties of Command Object
1. Connection Property :
• This property contains data about the connection string. It must be set on
the SqlCommand object before it is executed.
• For the command to execute properly, the connection must be open at the
time of execution.
• Calling :
cmd.ComandType =
CommandType.StoredProcedure
CommandType.TableDirect
CommandType.Text
Count Emp 10
Answer
ExecuteScalar Example
private void button1_click(object sender , EventAgrs e)
{
SqlConnection conn = new SqlConnection (“Data Source = .\\
SQLEXPRESS; AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security =
True”)
SqlCommand cmd = new SqlCommand( );
cmd.Connection = conn;
string str = “Select Max(Salary) from emp”; //Max
cmd.ComamndText = str;
conn.Open( );
txtMaxSal.Text = cmd.ExecuteScalar().ToString();
conn.Close();
ExecuteScalar Example
str = “Select Min(Salary) from emp”; //Min
cmd.ComamndText = str;
conn.Open( );
txtMinSal.Text = cmd.ExecuteScalar().ToString();
conn.Close();
conn.Open( );
txtAvgSal.Text = cmd.ExecuteScalar().ToString();
conn.Close();
ExecuteScalar Example
str = “Select Sum(Salary) from emp”; //Sum
cmd.ComamndText = str;
conn.Open( );
txtSumSal.Text = cmd.ExecuteScalar().ToString();
conn.Close();
conn.Open( );
txtCntEmp.Text = cmd.ExecuteScalar().ToString();
conn.Close();
ExecuteNonQuery
• To Execute Insert, Update, Delete queries.
• It returns number of rows affected.
Enter Std 1
Answer
OK
ExecuteScalar Example
private void button1_click(object sender , EventAgrs e)
{
int total = 0;
SqlConnection conn = new SqlConnection (“Data Source = .\\
SQLEXPRESS; AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security =
True”)
SqlCommand cmd = new SqlCommand( );
cmd.Connection = conn;
cmd.CommandText = “Delete from Stu where Std = ” + txtStd.Text;
conn.Open( );
total = cmd.ExecuteNonQuery( );
conn.Close();
MessageBox.Show(“Total Record Deleted = ” + total);
}
ExecuteReader
• When we execute the command object using ExecuteReader method that
time it returns DataReader.
• It returns DataReader which represents forward and readonly records.
• DataReader is used to retrieve a read-only, forward-only stream of data
from a database.
• We can not perform any insert, update and delete operations in the
DataReader.
• DataReader is opposite of DataSet.
• We can not move previous in the DataReader.
• When we just want to fill the data that time use DataReader.
• DataReader requires open connection.
• DataReader can hold one table at a time.
• DataReader have Item Collection.
ExecuteReader
• DataReader can increase application performance both by retrieving data
as soon as it is available, and (by default) storing only one row at a time in
memory, reducing system overhead.
• For example, Select Empno, Ename, Age from Emp then Empno is dr[0],
Ename is dr[1] and Age is dr[2].
• DataReader have read method to read next record.
• DataReader is set by command object’s ExecuteReader method.
SNo 7
SName Ritu
ExecuteReader Example
private void frmReader_Load(object sender , EventAgrs e)
{
SqlConnection conn = new SqlConnection (“Data Source = .\\
SQLEXPRESS; AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security =
True”)
SqlCommand cmd = new SqlCommand( );
SqlDataReader dr;
cmd.Connection = conn;
cmd.CommandText = “Select * from Stu”;
conn.Open( );
dr = cmd.ExecuteReader( );
ExecuteReader Example
while ( dr.Read() )
{
cmbSNo.Items.Add( dr[“SNo”].ToString() );
cmbSName.Items.Add( dr[“SName”].ToString() );
}
conn.close();
}
private void cmbSNo_SelectedIndexChanged(object sender , EventArgs e)
{
cmbSName.SelectedIndex = cmbSNo.SelectedIndex;
}
private void cmbSName_SelectedIndexChanged(object sender , EventArgs e)
{
cmbSNo.SelectedIndex = cmbSName.SelectedIndex;
}
DataAdapter Class
• It is associated Command and Connection objects.
• The DataAdapter is the class at the core of ADO.NET disconnected data
access.
• It is the middleman or bridge between the Database and a DataSet.
• The DataAdapter provides a set of methods and properties to retrieves and
save data between a DataSet and Database.
• The DataAdapter is used fill method to fill a DataTable or DataSet.
• The DataAdapter can commit the changes to the database by its Update
method.
• DataAdapter provides four properties that represent database commands :
1. SelectCommand
2. InsertCommand
3. DeleteCommand
4. UpdateCommand
DataAdapter Class
• When the Data Adapter fills a DataSet, it will create the necessary tables
and columns for the returned data.
• There are two ways to initialize it.
Relations Table
Schema Column
Constraint
Row
DataSet Class
• ADO.NET caches data locally on the client and store that data into
DataSet.
• The dataset is a disconnected, in-memory representation of data. The
DataSet is populated DataAdapter’s Fill method.
• It’s not exact copy the Database. It can be considered as a local copy of the
some portions of the database.
• The DataSet contains a collection of one or more DataTable object made
up of rows and columns of data.
• Tables can be identified in DataSet using DataSet’s Tables property.
• It also contains primary key, foreign key, constraint and relation
information about the data in the DataTable objects.
• Whatever operations are made by the user it is stored temporary in
the DataSet, when the use of this DataSet is finished, changes can be
made back to the central database for updating.
• DataSet are also fully XML featured.
DataSet Class Example
using System.Data.SqlClient;
private void frmDb1_Load (object sender , EventArgs e)
{
SqlConnection conn = new SqlConnection (“Data Source = .\\SQLEXPRESS;
AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security = True”);
Example :
• DataView dv = new DataView(ds.Tables(“Emp”))
• dv.RowFilter = “FirstName = ‘Bhavin’ ”;
• dv.RowFilter = “FirstName like ‘R%’ ”;
• dv.RowFilter = “Empno = 5”;
Demo of Sorting using ComboBox and DataGridView
4 Open Connection
7 Close Connection
Connected Mode Example
using System;
public class connectedDemo
{
static void Main(String[] args)
{
SqlDataReader rdr;
SqlConnection con;
SqlCommand cmd;
try
{
String connectionstring = “Data Source =
.\\SQLEXPRESS; AttachDbFilename =
D:\\DbGMIT.mdf; Integrated Security = True”;
con = new SqlConnection (connectionstring);
con.Open();
Connected Mode Example
String CommandText = “SELECT FirstName,
LastName” + “ FROM Employees” ;
cmd.Connection = con;
rdr = cmd.ExecuteReader();
while( rdr.Read() )
{
Console.WriteLine(rdr[FirstName].ToString() + “ “
+ rdr[“LastName”].ToString() );
}
con.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
}
}
Disconnected Mode
1 Create Connection
7 Close Connection
Disconnected Mode Example
using System;
public class DisconnectedDemo
{
static void Main(String[] args)
{
String connectionstring = “Data Source =
.\\SQLEXPRESS; AttachDbFilename =
D:\\DbGMIT.mdf; Integrated Security = True”;
//Create a connection String
SqlConnection con = new SqlConnection
(connectionstring);
// Open Connection
con.Open();
//Create a new command Object
SqlCommand cmd = new SqlCommand(“SELECT * FROM
Employees” , con);
Disconnected Mode Example
//Create adapter to Fill / Update dataset
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
//Create and fill Employee Table in dataset
Dataset ds = new Dataset();
adapter.Fill(ds , “Employees”);
//Display Data From Employee
Console.WriteLine(“Current DATA in EMPLOYEE table of
dataset”);
int count = 0;
Disconnected Mode Example
while(count <= ds.Tables[0].Rows.Count - 1)
{
Console.WriteLine(ds.Tables[0].Rows[count][0] +
“ “ + ds.Tables[0].Rows[count][1] + “ “ + ds.Tables[0].Rows[count][2] + “ “ +
ds.Tables[0].Rows[count][3]);
count = count + 1;
}
//ADD new row in DataSet
DataRow dr;
dr = ds.Tables[0].NewRow();
dr[“LastName”] = 2;
dr[“FirstName”] = “Demo”;
dr[“Title”] = “Demo”;
dr[“Address”] = “Demo”;
ds.Tables[0].Rows.Add(dr);
Disconnected Mode Example
//Use of CommandBuilder to set various command of adapter
SqlCommandBuilder builder;
builder = new SqlCommandBuilder (adapter);
adapter = builder.DataAdapter;
//Close Connection
con.Close();
}
}
Data Binding
• Data Binding refers to the how we bind control to the database.
• There are three ways to bind data.
1. Manual Binding :
• Manual binding means manual coding and refers steps connection,
command, data adapter, dataset.
Manual Binding - Example
using System.Data;
using System.Data.SqlClient;
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection(“ Data Source = C:\\
users\\Application3\\db1.mdf ”);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender , EventArgs e)
{
SqlCommand cmd = new SqlCommand (“Select * from
Dept ”);
Manual Binding - Example
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.Connection = conn;
da.SelectCommand = cmd;
da.Fill(ds);
cmbDept.DataSource = ds.Tables[0];
cmbDept.DisplayMember = “DeptName”;
}
private void cmbDept_SelectedIndexChanged(object sender ,
EventArgs e)
{
dataGridView1.DataSource = “ ” ;
SqlCommand cmd2 = new SqlCommand();
Manual Binding - Example
cmd2.Connection = conn;
cmd2.CommandText = “Select EmpNo , EmpName ,
Salary from emp , dept where deptname = ‘” +
cmbDept.Text + “’ and Dept.DeptNo = Emp.DeptNo ” ;
SqlDataAdapter da2 = new SqlDataAdapter();
da2.SelectCommand = cmd2;
DataSet ds2 = new DataSet();
da2.Fill(ds2);
dataGridView1.DataSource = ds2.Tables;
}
}
Simple Binding
• In Simple data bind, data binds using Data binding property.
• It is easiest way to bind data with controls. We have to configure each and
every control differently.
• Simple Data binding requires less coding.
Rno 1
Name Rahul
Fees 12000
dataGridView1.DataSource = ds.Tables;
}
Example
• ADO.NET main program, 4 buttons for Navigations, 4 buttons for Add-
Update-Delete-Cancel.
RollNo 1
Name Rahul
DOB 01/01/2000
Std
3. Draw and explain ADO.NET architecture with its new features. (Summer
2016 , Winter 2015).
4. What was ADO Technology? How it differs from ADO.NET Technology?
Explain. (Summer 2016)
Questions
5. Explain usage of following ADO.NET objects with their methods.
(Summer - 2016)
• SqlDataAdapter
• SqlCommand object
• Dataset
6. What is SqlDataReader? Explain it with relevant example. (Summer -
2016)
7. List and Explain common namespace used for ADO.NET. Also list most
common classes in those namespace. (Summer - 2015)
8. Write a short note : ADO.NET (Winter - 2014)
9. Explain data sets and data binding related to ADO.NET. (Winter - 2014)
10. List and Explain important classes of ADO.NET. (Summer – 2014 ,
Winter - 2013)
11. What do you mean by managed provider? How managed provides are
supported in ADO.NET. (Winter - 2016)
Questions
12. Explain following features of ADO.NET ? (Winter - 2013)
• Managed provider
• Disconnected data access
13. Write a ADO.NET program which shows record from student_master
(name , email , city , phone) on console. (Winter - 2013).
14. Write a ADO.NET program which shows record from student_master
(name , email , city , phone) on DataGridView and GridView. (Winter -
2016)
15. Draw and explain ADO.NET architecture in detail. (Summer - 2017)
16. Explain usage of following ADO.NET objects with their methods.
(Summer – 2017).
• SqlDataAdapter
• SqlCommand object
• Dataset
17. Write a C# code to bind data from given table to ComboBox Control
using DataAdapter. Table : Student (EnNo , Name). (Summer - 2017)
You
a n k
T h