2. 2
ADO.Net
• ADO.Net is an object model used to establish connection between
application and data sources.
• Application: Any application developed using .NET framework can
use ADO.net
Window Application, Web Application, Web services, console application
• Data sources: databases and XML files
• ADO.Net consists of classes that can be used to connect, retrieve and
manipulate data.
3. 3
Fundamental Component
• Main components used for accessing and manipulating data are Data Provider
and the Dataset
The Dataset represents disconnected architecture.
o It is in memory presentation of the data
o It is disconnected from the data source and doesn’t need to know where the data it holds
come from.
o Once you collect the data from database and store it in a dataset it doesn’t need to know
where the data is came from. Once the dataset get populated we don’t need to keep up
connected with database. If the connection is loss or connection is closed the data will
still be available in dataset.
The Data Providers represent connected architecture.
o They allow us to connect to the data source, and to execute SQL commands against it.
4. 4
.NET Data Providers
• ADO.Net allows us to connect with various types of data databases
• There is a data provider for:
SQL Server
OLE DB data source - (e.g Microsoft access database, older version of SQL servers,
oracle)
ODBC-compliant data sources – Old
• Each provider exists in namespace within the System.Data namespace, and consists a
number of classes.
• The classes for the SQL Server Data Provider are found in the System.Data.SqlClient
namespace.
• The classes for the OLE DB Data Provider are found in the System.Data.OleDb namespace.
5. 5
Data Provider Component
• Each .NET Data Provider consists of four main components.
Connection – used to connect to data source
Command – used to execute a command(query) against the data source and
retrieve a DataReader or Dataset, or to execute and INSERT, UPDATE, or
DELETE command against data source.
DataReader – a forward-only, read-only connected resultset.
o It is used to store the result of SELECT query. You can only read in one
direction. So you cannot alter.
DataAdapter – used to populate a Dataset with a data from the data source,
and to update the data source.
o It act as an interface between data source and dataset.
o DataAdapter fetches the data from the database and store it in the dataset.
o Whenever you make any changes in a dataset, you have to update that
changes back to database.
7. 7
Connection
• Connection object provides connectivity to the database/ data source.
• It is used to open a connection to the database on which commands will be
executed.
• They are manifested in each data provider as either the SqlConnection (for SQL
Server Data Provider) or the OleDbConnection (for the OLE DB Data Provider).
8. 8
Establishing Connection
• The connection class is instantiated,
• A connection string is set,
• And the connection is opened.
• Once the connection is opened, commands may be executed over the connection
to retrieve or manipulate data in the database.
• Once we are done with the connection, it must be closed to release the resource.
9. 9
Connection Classes
• The SqlConnection class is used to connect a Microsoft SQL server 7.0 or
greater database.
• For any other database that supports OLE DB, such as Microsoft Access, Oracle, or
previous version of SQL Server, use the OleDbConnection class.
10. 10
Methods and Properties
• Methods
Open()
Close()
• Property
ConnectionString: A connection string contains initialization information that is passed as a
parameter from the data provider to the data source.
12. 12
Microsoft Access database Connection
OleDbConnection oleDbConnection = new OleDbConnection();
oleDbConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:UsersRAYAOneDriveDocumentsresultdb.accdb";
try
{
if (oleDbConnection.State == System.Data.ConnectionState.Open)
oleDbConnection.Close();
oleDbConnection.Open();
MessageBox.Show("Access DB Connection successfully");
}
catch (Exception ex)
{
MessageBox.Show("Access DB Connection Fail"+ ex.Message.ToString());
}
finally
{
oleDbConnection.Close();
}
13. 13
Command – EXECUTE DATABASE COMMANDS/QUERIES
• A command object enables database commands, such as T-SQL
commands/queries or stores procedures, to be executed against the database.
• Commands require an instance of a connection object in order to connect to the
database and execute a command.
• The command classes are manifested as either the SqlCommand or the
OleDbCommand.
14. 14
Command class properties
• Connection – an instance of connection class
• CommandType
CommandType.Text – a SQL statement
CommandType.TableDirect – a table name whose columns are returned
CommandType.StoredProcedure – the name of stored procedure
• CommandText – a string value that represents the command that will be executed
against the data source
15. 15
Command class methods
• ExecuteNonQuery() is used for executing commands that do not return a result
set, such as update, insert, or delete commands.
The ExecuteNonQuery() method returns an integer value indicating the
number of rows affected by the command.
• ExecuteReader() returns an object that implements the IDataReader interface,
such as an OleDbReader or a SQLDataReader.
• The ExecuteScalar() method return the first column of the first row in the result
set; all other columns and rows are ignored.
this method is particularly useful for returning aggregate values, such as the
result of a SELECT COUNT(*) SQL statement.
16. 16
ADO.Net DataReader
• It is a forward-only, read-only connected resultset
• We can’t navigate through it at random, and we can’t use it to update the data
source.
• It therefore allows extremely fast access to data that we just want to iterate through
once.
• The datareaders achieve their high performance by utilizing an open connection to
the database. It’s not possible to create a disconnected DataReader.
17. 17
ADO.Net DataReader
• Datareaders deal with a single row at a time; they don’t provide bulk data retreaval.
• It is recommended to use the DataReader (rather than the DataSet) whenever
possible.
• A DataReader can only be returned from a call to the ExecuteReader method of a
command object; we can’t instantiate it directly.
18. 18
The ExecuteReader Method
• All begins, with a call to ExecuteReader.
• This method executes the SQL or stored procedure that the Command object
represents and returns a datareader object.
19. 19
Properties
• HasRows: It is used to get a value that indicates whether the
SQLDataReader/OleDbDataReader contains one or more rows.
• FIeldCount: It is used to get the number of columns in the current row.
20. 20
Methods
• Read()
We traverse over the records by using the Read method on the DataReader. This has the effect of moving the
DataReader to the next record.
When a DataReader is first returned, it is actually positioned before the first record in the result set. This being
the case, we must call Read before trying to access any of the values in the DataReader columns. Failure to do
so raises an exception.
In loop, when each time Read is called we advance to the next record. If Read is called and there are no more
record left, then false is returned and the while loop terminates.
21. 21
DataReader – GridView Example 1
using (SqlConnection xcn = new SqlConnection(ConString)){
try {
if(xcn.State == System.Data.ConnectionState.Open)
xcn.Close();
xcn.Open();
//MessageBox.Show("Connection Success");
String query = "SELECT * FROM Book";
SqlCommand cmd = new SqlCommand(query, xcn);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == true) {
dataGridView1.Rows.Clear();
while (reader.Read()){
dataGridView1.Rows.Add(reader[0], reader[1], reader[2], reader[3], reader[4] );
}
}
else{
MessageBox.Show("No Record Found");
}
}catch (Exception ex){
MessageBox.Show("Connection Fail");
}finally {
xcn.Close();
}
}
22. 22
DataReader – GridView Example 2
using (SqlConnection xcn = new SqlConnection(ConString)){
try {
if(xcn.State == System.Data.ConnectionState.Open)
xcn.Close();
xcn.Open();
//MessageBox.Show("Connection Success");
String query = "SELECT * FROM Book";
SqlCommand cmd = new SqlCommand(query, xcn);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == true) {
dataGridView1.Rows.Clear();
DataTable dt = new DataTable();
dt.Load(dataReader);
dataGridView1.DataSource = dt;
}
else{
MessageBox.Show("No Record Found");
}
}catch (Exception ex){
MessageBox.Show("Connection Fail");
}finally {
xcn.Close();
}
}
24. 24
DataAdapter
• Dataset
Inmemory representation of the data
It store data
It also include table design (column data types, columns constraints, relationship between the
tables, etc. )
• DataAdapter
Act as a bridge between disconnected dataset and data source
It has four commands (InsertCommand, UpdateCommand, DeleteCommand, SelectCommand)
It works in two ways i.e it is used to populate the dataset as well as update the changes made in
dataset back to data source
It is strictly tied with the dataset class to create inmemory representation of the data
25. 25
Fill Method
• This method populates the specified DataSet or DataTable object, retrieve a set of records
from the database.
• The Fill method connects to the database using either the connection string or a connection object,
• It retrieves the records by executing the SQL statement specified, either using a string parameter or a
command object
• It then closes the connection, freeing the server’s resources.
• N.B: you don’t need to open and close connection explicitly.
26. 26
Update Method
• The Update method goes through each record within the provided DataSet object,
analyzing the RowState value and calling the respective SQL command when this
value is different from the unchanged state.
• We need SQL commands to perform these updates, inserts, and deletes.
• For that CommandBUilder object is used
27. 27
Dataset in ADO.Net
• The DataSet is the centerpiece of disconnected, data-driven application.
• It in an in-memory representation of a complete set of data, including tables, relationships, and
constraints.
Whenever we populate the dataset, it get stored in a memory. Not only fetches the data but also
fetches its complete table design(relationships and constraints)
• The DataSet does not maintain a connection to a data source, enabling true disconnected data
management.
• The data in a DataSet can be accessed, manipulated, updated, or deleted, and then reconciled with the
original data source.
• Since the DataSet is disconnected from the source, there is less contention for valuable resources, such
as database connections, and less record locking
28. 28
Populating DataSet
• ADO.NET provides an object, the DataAdapter, which is what we use with the DataSet.
• The DataAdapter.Fill method is the trigger that fires the SqlDataAdapter.SelectCommand.
• To populate a DataSet with a new DataTAble we can use the Fill method and pass in a
DataSet as an argument.
• The Fill method will create a DataTable in the DataSet and fill it with the result of the T-
SQL command
29. 29
DataTable
• A DataTable stores data in a similar form to a database table: data is stored a set of fields
(columns) and records (rows).
• The DataTable class is a central class in the ADO.NET architecture; it can be used
independently, and in Dataset Objects.
If you want to fetch data from single table of a database, you can use DataTable only.
If you are fetching data from more than one table, you can use DataSet
• A DataTable consists of a columns collection, a Row collection, and a Constraints collection.
30. 30
DataView
• DataView is customerzied view of DataSet
• It allows you to customize the view for your data in a dataset
• It enables developers to filter and sort data in a dataset
31. 31
Steps to use DataAdapter and DataSet
1. Create a connection to your SQL Server database using the SqlConnection class.
2. Create a DataAdapter and CommandBuilder:
3. Instantiate a DataSet to store the data retrieved from the databases
SqlConnection xcn = new SqlConnection(Connection String);
string query = "SELECT * FROM Book";
SqlCommand cmd = new SqlCommand(query, xcn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder();
dataAdapter = new SqlDataAdapter();
commandBuilder.DataAdapter = dataAdapter;
dataAdapter.SelectCommand = cmd;
dataSet = new DataSet();
32. 32
Steps to use DataAdapter and DataSet
4. Use the Fill method of the SqlDataAdapter to populate the DataSet with data from the
database.
5. If you want to display the data in your Windows Form, you can bind the DataSet to controls
like DataGridView or ComboBox.
dataAdapter.Fill(dataSet, "Book");
dataGridView1.DataSource = dataSet;
dataGridView1.DataMember = "Book";
33. 33
Steps to use DataAdapter and DataSet
6. Perform Operations on the Data: You can manipulate the data within the DataSet as needed.
Make changes, additions, or deletions as necessary.
7. Update the Database: If you've made changes to the data within the DataSet and want to
persist those changes back to the database, you can use the Update method of the
SqlDataAdapter.
dataAdapter.Update(dataSet, "Book");