SlideShare a Scribd company logo
1 of 35
CS 2104: Visual
Programming
Lecture 14: Data Access
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
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
.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
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.
6
ADO.Net Architecture
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
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
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
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.
11
SQL Server database Connection
SqlConnection xcn = new SqlConnection();
xcn.ConnectionString = "Data Source=DESKTOP-D7LGMARSQLEXPRESS;Initial
Catalog=library;Integrated Security=True";
try
{
if (xcn.State == System.Data.ConnectionState.Open)
xcn.Close();
xcn.Open();
MessageBox.Show("Connection successfully");
}catch(Exception ex)
{
MessageBox.Show("Connection Fail");
}
finally
{
xcn.Close();
}
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
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
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
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
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
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
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
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
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
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
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();
}
}
23
DataAdapter in ADO.Net
• A bridge between the disconnected dataset and the data source
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
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
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
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
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
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
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
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
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
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");
34
private void Form2_Load(object sender, EventArgs e)
{
try
{
SqlConnection xcn = new SqlConnection(ConString);
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();
dataAdapter.Fill(dataSet, "Book");
dataGridView1.DataSource = dataSet;
dataGridView1.DataMember = "Book";
}
catch (Exception ex)
{
MessageBox.Show("Connection Fail");
}
35
private void button1_Click(object sender, EventArgs e)
{
try
{
dataAdapter.Update(dataSet, "Book");
MessageBox.Show("Book Record Updated");
}
catch(Exception ex)
{
MessageBox.Show("Update Fail: "+ ex.Message);
}
}

More Related Content

Similar to LECTURE 14 Data Access.pptx

Similar to LECTURE 14 Data Access.pptx (20)

Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 
Ado.net
Ado.netAdo.net
Ado.net
 
Ado.net
Ado.netAdo.net
Ado.net
 
ADO.net control
ADO.net controlADO.net control
ADO.net control
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Marmagna desai
Marmagna desaiMarmagna desai
Marmagna desai
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Ado
AdoAdo
Ado
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 
Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Ado dot net complete meterial (1)
Ado dot net complete meterial (1)
 
3-ADO.NET.pdf
3-ADO.NET.pdf3-ADO.NET.pdf
3-ADO.NET.pdf
 
ado.net
ado.netado.net
ado.net
 
5.C#
5.C#5.C#
5.C#
 
Database programming in vb net
Database programming in vb netDatabase programming in vb net
Database programming in vb net
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
Connected data classes
Connected data classesConnected data classes
Connected data classes
 

Recently uploaded

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 

Recently uploaded (20)

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 

LECTURE 14 Data Access.pptx

  • 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.
  • 11. 11 SQL Server database Connection SqlConnection xcn = new SqlConnection(); xcn.ConnectionString = "Data Source=DESKTOP-D7LGMARSQLEXPRESS;Initial Catalog=library;Integrated Security=True"; try { if (xcn.State == System.Data.ConnectionState.Open) xcn.Close(); xcn.Open(); MessageBox.Show("Connection successfully"); }catch(Exception ex) { MessageBox.Show("Connection Fail"); } finally { xcn.Close(); }
  • 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(); } }
  • 23. 23 DataAdapter in ADO.Net • A bridge between the disconnected dataset and the data source
  • 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");
  • 34. 34 private void Form2_Load(object sender, EventArgs e) { try { SqlConnection xcn = new SqlConnection(ConString); 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(); dataAdapter.Fill(dataSet, "Book"); dataGridView1.DataSource = dataSet; dataGridView1.DataMember = "Book"; } catch (Exception ex) { MessageBox.Show("Connection Fail"); }
  • 35. 35 private void button1_Click(object sender, EventArgs e) { try { dataAdapter.Update(dataSet, "Book"); MessageBox.Show("Book Record Updated"); } catch(Exception ex) { MessageBox.Show("Update Fail: "+ ex.Message); } }