SlideShare uma empresa Scribd logo
1 de 47
Advanced Programming
Methodology in C# -
Database
ADO.NET
Introduction
Before .NET, developers used data access technologies
such as ODBC, OLE DB, and ActiveX Data Object
(ADO). With the introduction of .NET, Microsoft created
a new way to work with data, called ADO.NET.
ADO.NET is a set of classes exposing data access
services to .NET programmers, providing a rich set
of components for creating distributed, data-sharing
applications. ADO.NET is an integral part of the
.NET Framework and provides access to relational,
XML, and application data.
Introductions (Cont.)
ADO.NET classes are found in System.Data.dll.
This technology supports a variety of
development needs, including the creation of
front-end database clients and middle-tier
business objects used by applications, tools,
languages, and Internet browsers. Hence,
ADO.NET helps connect the UI, or presentation
layer, of your application with the data source or
database.
ADO.NET and .NET Base Class
Library
A data set (a DataSet object) can hold large
amounts of data in the form of tables (DataTable
objects), their relationships (DataRelation
objects), and constraints (Constraint objects) in
an in-memory cache, which can then be
exported to an external file or to another data
set. Since XML support is integrated
into ADO.NET, you can produce XML schemas
and transmit and share data using XML
documents.
ADO.NET and .NET Base Class
Library (Cont.)
ADO.NET Architecture
ADO.NET offers two types of architectural components
to build data-centric applications: connected
and disconnected. Within Microsoft .NET Framework,
ADO.NET is housed in the namespace
System.Data (the assembly name is System.Data.dll), so
all the classes and functions for connected and
disconnected components live in the same namespace.
Hence, it is important to add a reference of
System.Data to your application irrespective of the
connected or disconnected architecture style you
have chosen or will choose later.
ADO.NET Architecture (Cont.)
Connected Data Objects
ADO.NET’s connected architecture relies on a
consistent database connection to access data and
perform any operations on the retrieved data. ADO.NET
offers the following objects to help you build your
application with a connected architecture:
• Connection
• Command
• DataReader
Connection
Before you can do anything useful with a database, you
need to establish a session with the database server.
You do this with an object called a connection. Here
below are data providers that provided by Microsoft:
Connection (Cont.)
String connString = string.Empty;
connString = “server = sqlexpress; integrated security =
true”; // Window Authentication
connString = “server = sqlexpress; user id = sa;
password = 1234567”; // SQL Authentication
SqlConnection conn = new SqlConnection(connString);
Conn.Open();
//
// Code
//
Conn.Close();
Command

Once you’ve established a connection to
the database, you want to start interacting
with it and getting it doing something
useful for you. You may need to retrieve,
add, update, or delete some data, or
perhaps modify the database in some
other way, usually by running a query.
Whatever the task, it will inevitably involve
a command.
Command (Cont.)
Command (Cont.)
Commands aren’t much use unless you can execute
them, so let’s look at that now. Commands have several
different methods for executing SQL. The differences
between these methods depend on the results you
expect from the SQL. Queries return rows of data
(result sets), but the INSERT, UPDATE, and DELETE
statements don’t.
DataReader
A data reader is a fast, unbuffered,
forward-only, read-only connected
stream that retrieves data on a per-
row basis. It reads one row at a time as
it loops through a result set. You can’t
directly instantiate a data reader;
instead, you create one with the
ExecuteReader method of a command.
DataReader (Cont.)
// Connection string
String connString = @"server=.sql2012;
database=AdventureWorks;Integrated
Security=SSPI";
// Query
string sql = @"select Name from Production.
Product";
// Create connection
SqlConnection conn = new SqlConnection(connString);
// Open connection
conn.Open();
DataReader (Cont.)
// Create command
SqlCommand cmd = new SqlCommand(sql, conn);
// Create data reader
SqlDataReader rdr = cmd.ExecuteReader();
// Loop through result set
while (rdr.Read())
{
   // Add to listbox - one row at a time
   lbxProduct.Items.Add(rdr[0]);
}
// Close data reader
rdr.Close();
conn.Close();
Disconnected Data Objects
ADO.NET’s disconnected architecture offers flexible
application design and helps organizations save
database connections. Hence, data can be retrieved
and then stored locally on the device in the form of a
DataSet object. The retrieved DataSet can be modified
by users on their local devices such as laptops,
handhelds, tablets, and so on, and once that’s done,
they can sync the changes into the central data source.
Disconnected architecture utilizes expansive resources
like Connection in a very optimum way (that is, to open
late and close early).
Disconnected Data Objects (Cont.)
ADO.NET offers the following objects to help you build
your application with a disconnected architecture:
• DataSet
• DataAdapter
• DataTable
• DataColumn
• DataRow
DataSet
you’ll look at a new object for accessing data,
the data set. Unlike data readers; a distinct
ADO.NET component used by all data providers.
Data sets are completely independent of and
can be used either connected to or
disconnected from data sources. Their
fundamental purpose is to provide a relational
view of data stored in an in-memory cache.
DataSet (Cont.)
DataSet vs DataReader
If you simply want to read and display data,
then you need to use only a data reader, as
you saw in the previous chapter,
particularly if you’re working with large
quantities of data. In situations where you
need to loop through thousands or millions
of rows, you want a fast sequential reader
(reading rows from the result set one at a
time), and the data reader does this job in
an efficient way.
DataSet vs DataReader (Cont.)
If you need to manipulate the data in any way
and then update the database, you need to use
a data set. A data adapter fills a data set by
using a data reader; additional resources are
needed to save data for disconnected use. You
need to think about whether you really need a
data set; otherwise, you’ll just be wasting
resources. Unless you need to update the data
source or use other data set features such as
reading and writing to XML files, exporting
database schemas, and creating XML views of a
database, you should use a data reader.
DataAdapter
When you first instantiate a data set, it contains no
data. You obtain a populated data set by passing it to
a data adapter, which takes care of connection details
and is a component of a data provider. A data set isn’t
part of a data provider. It’s like a bucket, ready to be
filled with water, but it needs an external pipe to let the
water in. In other words, the data set needs a data
adapter to populate it with data and to support access
to the data source. Each data provider has its own data
adapter in the same way that it has its own connection,
command, and data reader.
DataAdapter (Cont.)
DataAdapter (Cont.)
The data adapter constructor is overloaded. You can
use any of the following to get a new data adapter.
We’re using the SQL Server data provider, but the
constructors for the other data providers are
analogous.
SqlDataAdapter da = new SqlDataAdapter();
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(sql,
                           connString);
DataAdapter (Cont.)
So, you can create a data adapter in four ways:
• You can use its parameterless constructor
   (assigning SQL and the connection later).
• You can pass its constructor a command
   (here, cmd is a SqlCommand object).
• You can pass a SQL string and a connection.
• You can pass a SQL string and a connection
   string.
DataSet with DataAdapter
// Connection string
string connString = @"server=sqlexpress;
database=AdventureWorks; Integrated Security=true";
// Query
string sql = @"select Name,ProductNumber
from Production.Product where SafetyStockLevel > 600";
// Create connection
SqlConnection conn = new SqlConnection(connString);
// Open connection
conn.Open();
DataSet with DataAdapter (Cont.)
// Create Data Adapter
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
// Create Dataset
DataSet ds = new DataSet();
// Fill Dataset
da.Fill(ds, "Production.Product");
// Display data
gvProduct.DataSource = ds.Tables["Production.Product"];
//Connection close
conn.Close();
DataTable
A data table is an instance of the class
System.Data.DataTable. It’s conceptually analogous to a
relational table. You can access these nested collections
via the Rows and Columns properties of the data table.
A data table can represent a stand-alone independent
table, either inside a data set, as you’ll see in this
chapter, or as an object created by another method, as
you saw in the previous chapter when a data table was
returned by calling the GetSchemaTable method on a
data reader.
DataTable (Cont.)
DataTable table = new DataTable("ParentTable");
DataColumn column;
DataRow row;

column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
column.ReadOnly = true;
column.Unique = true;
table.Columns.Add(column);
DataTable (Cont.)
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ParentItem";
column.AutoIncrement = false;
 column.Caption = "ParentItem";
 column.ReadOnly = false;
column.Unique = false;
 table.Columns.Add(column);

DataColumn[] PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = table.Columns["id"];
table.PrimaryKey = PrimaryKeyColumns;
DataTable (Cont.)
dataSet = new DataSet();
dataSet.Tables.Add(table);

for (int i = 0; i<= 2; i++)
{
  row = table.NewRow();
  row["id"] = i;
  row["ParentItem"] = "ParentItem " + i;
  table.Rows.Add(row);
}
DataColumn
A data column represents the schema of a column
within a data table and can then be used to set or get
column properties. For example, you could use it to set
the default value of a column by assigning a value to
the DefaultValue property of the data column. You
obtain the collection of data columns using the data
table’s Columns property, whose indexer accepts either
a column name or a zero-based index, for example
(where dt is a data table):
DataColumn col = dt.Columns["ContactName"];
DataColumn col = dt.Columns[2];
DataRow
A data row represents the data in a row. You can
programmatically add, update, or delete rows in
a data table. To access rows in a data table, you
use its Rows property, whose indexer accepts a
zero-based index, for example (where dt is a
data table):
DataRow row = dt.Rows[2];
Understanding .NET Data
Providers
ADO.NET consists of various data providers that allow
an easy and predefined object model to communicate
with various industry databases such as SQL Server,
Oracle, Microsoft Access, and many others.
Understanding .NET Data
Providers
For example, if you use SQL Server, you should use the
SQL Server data provider (System.Data.SqlClient)
because it’s the most efficient way to access SQL
Server. The OLE DB data provider supports access to
older versions of SQL Server as well as to other
databases, such as Access, DB2, MySQL, and Oracle.
However, native data providers (such as
System.Data.OracleClient) are preferable for
performance, since the OLE DB data provider works
through two other layers, the OLE DB service
component and the OLE DB provider, before reaching
the data source.
Understanding .NET Data
Providers
Understanding .NET Data
Providers
Each .NET data provider is designed to do the following
two things very well:
• Provide access to data with an active connection to
the data source
• Provide data transmission to and from disconnected
data sets and data tables
Understanding .NET Data
Providers
Database connections are established by using the data
provider’s Connection class (for example,
System.Data.SqlClient.SqlConnection). Other
components such as data readers, commands, and data
adapters support retrieving data, executing SQL
statements, and reading or writing to data sets or data
tables, respectively.
Understanding the SQL Server Data
Provider
The .NET data provider for SQL Server is in the
System.Data.SqlClient namespace. Although you can
use System.Data.OleDb to connect with SQL Server,
Microsoft has specifically designed the
System.Data.SqlClient namespace to be used with SQL
Server, and it works in a more efficient and optimized
way than System.Data.OleDb. The reason for this
efficiency and optimized approach is that this data
provider communicates directly with the server using
its native network protocol instead of through multiple
layers.
Commonly Used SqlClient Classes
Understanding the OLE DB Data Provider

• Outside .NET, OLE DB is still Microsoft’s high-
performance data access technology.
• You can use this data provider to access data stored in
any format, so even in ADO.NET it plays an important
role in accessing data sources that don’t have their own
ADO.NET data providers.
Commonly Used OleDb Classes
Understanding the ODBC Data Provider

• ODBC was Microsoft’s original general-purpose data access
technology.
• The ODBC architecture is essentially a three-tier process. An
application uses ODBC functions to submit database requests.
ODBC converts the function calls to the protocol (call-level
interface) of a driver specific to a given data source. The driver
communicates with the data source, passing any results or errors
back up to ODBC. Obviously, this is less efficient than a database-
specific data provider’s direct communication with a database,
so for performance it’s preferable to avoid the ODBC data
provider, since it merely offers a simpler interface to ODBC but
still involves all the ODBC overhead.
Commonly Used Odbc Classes
Summary
This chapter you will understand about two main types
of data access that provided from ADO.NET; Connected
Data Objects and Disconnected Data Objects. Both
types have their own advantages to fulfill the full-
functionality to access data. Both types their own main
components.
• Connected Data Objects : Connection, Command,
   and DataReader.
• Disconnected Data Objects : DataSet, DataAdapter,
   DataTable, DataColumn and DataRow.

Mais conteúdo relacionado

Mais procurados (20)

Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Database Connection
Database ConnectionDatabase Connection
Database Connection
 
Data base connectivity and flex grid in vb
Data base connectivity and flex grid in vbData base connectivity and flex grid in vb
Data base connectivity and flex grid in vb
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Client Server Architecture ppt
Client Server Architecture pptClient Server Architecture ppt
Client Server Architecture ppt
 
sets and maps
 sets and maps sets and maps
sets and maps
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Database connectivity and web technologies
Database connectivity and web technologiesDatabase connectivity and web technologies
Database connectivity and web technologies
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Sql Server Basics
Sql Server BasicsSql Server Basics
Sql Server Basics
 
Web api
Web apiWeb api
Web api
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 

Destaque

Ontop: Answering SPARQL Queries over Relational Databases
Ontop: Answering SPARQL Queries over Relational DatabasesOntop: Answering SPARQL Queries over Relational Databases
Ontop: Answering SPARQL Queries over Relational DatabasesGuohui Xiao
 
1 introduction
1   introduction1   introduction
1 introductionNgeam Soly
 
Chapter 2: Ms SQL Server
Chapter 2: Ms SQL ServerChapter 2: Ms SQL Server
Chapter 2: Ms SQL ServerNgeam Soly
 
Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5Ehtsham Khan
 
Entity framework and how to use it
Entity framework and how to use itEntity framework and how to use it
Entity framework and how to use itnspyre_net
 
Dotnet differences compiled -1
Dotnet differences compiled -1Dotnet differences compiled -1
Dotnet differences compiled -1Umar Ali
 
05 entity framework
05 entity framework05 entity framework
05 entity frameworkglubox
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentalsMadhuri Kavade
 
Entity Framework and Domain Driven Design
Entity Framework and Domain Driven DesignEntity Framework and Domain Driven Design
Entity Framework and Domain Driven DesignJulie Lerman
 
Latest Advance Animated Ado.Net With JDBC
Latest Advance Animated Ado.Net With JDBC Latest Advance Animated Ado.Net With JDBC
Latest Advance Animated Ado.Net With JDBC Tarun Jain
 
ASP.NET 10 - Data Controls
ASP.NET 10 - Data ControlsASP.NET 10 - Data Controls
ASP.NET 10 - Data ControlsRandy Connolly
 
Relational Database to RDF (RDB2RDF)
Relational Database to RDF (RDB2RDF)Relational Database to RDF (RDB2RDF)
Relational Database to RDF (RDB2RDF)EUCLID project
 
Vb.net session 12
Vb.net session 12Vb.net session 12
Vb.net session 12Niit Care
 
Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debuggingsalissal
 

Destaque (20)

For Beginers - ADO.Net
For Beginers - ADO.NetFor Beginers - ADO.Net
For Beginers - ADO.Net
 
Ado.net
Ado.netAdo.net
Ado.net
 
ADO.NET -database connection
ADO.NET -database connectionADO.NET -database connection
ADO.NET -database connection
 
Ontop: Answering SPARQL Queries over Relational Databases
Ontop: Answering SPARQL Queries over Relational DatabasesOntop: Answering SPARQL Queries over Relational Databases
Ontop: Answering SPARQL Queries over Relational Databases
 
1 introduction
1   introduction1   introduction
1 introduction
 
Chapter 2: Ms SQL Server
Chapter 2: Ms SQL ServerChapter 2: Ms SQL Server
Chapter 2: Ms SQL Server
 
Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5
 
Entity framework and how to use it
Entity framework and how to use itEntity framework and how to use it
Entity framework and how to use it
 
Ado .net
Ado .netAdo .net
Ado .net
 
Dotnet differences compiled -1
Dotnet differences compiled -1Dotnet differences compiled -1
Dotnet differences compiled -1
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
Entity Framework and Domain Driven Design
Entity Framework and Domain Driven DesignEntity Framework and Domain Driven Design
Entity Framework and Domain Driven Design
 
Latest Advance Animated Ado.Net With JDBC
Latest Advance Animated Ado.Net With JDBC Latest Advance Animated Ado.Net With JDBC
Latest Advance Animated Ado.Net With JDBC
 
ASP.NET 10 - Data Controls
ASP.NET 10 - Data ControlsASP.NET 10 - Data Controls
ASP.NET 10 - Data Controls
 
Relational Database to RDF (RDB2RDF)
Relational Database to RDF (RDB2RDF)Relational Database to RDF (RDB2RDF)
Relational Database to RDF (RDB2RDF)
 
Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
Vb.net session 12
Vb.net session 12Vb.net session 12
Vb.net session 12
 
Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debugging
 
Debugging in .Net
Debugging in .NetDebugging in .Net
Debugging in .Net
 

Semelhante a Advanced C# ADO.NET Database Programming

Semelhante a Advanced C# ADO.NET Database Programming (20)

Ado.net
Ado.netAdo.net
Ado.net
 
ADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaADO .NET by Sonu Vishwakarma
ADO .NET by Sonu Vishwakarma
 
Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net Architecture
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to ado
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
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
AdoAdo
Ado
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.Net
 
Ado
AdoAdo
Ado
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 
Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Ado dot net complete meterial (1)
Ado dot net complete meterial (1)
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
Unit4
Unit4Unit4
Unit4
 
3-ADO.NET.pdf
3-ADO.NET.pdf3-ADO.NET.pdf
3-ADO.NET.pdf
 
Csharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxCsharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptx
 

Mais de Ngeam Soly

សន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាម
សន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាមសន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាម
សន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាមNgeam Soly
 
អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...
អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...
អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...Ngeam Soly
 
មេរៀនៈ Data Structure and Algorithm in C/C++
មេរៀនៈ Data Structure and Algorithm in C/C++មេរៀនៈ Data Structure and Algorithm in C/C++
មេរៀនៈ Data Structure and Algorithm in C/C++Ngeam Soly
 
Chapter01 introduction
Chapter01 introductionChapter01 introduction
Chapter01 introductionNgeam Soly
 
Slide for presentation
Slide for presentation Slide for presentation
Slide for presentation Ngeam Soly
 
Accounting assingment year ii
Accounting assingment year iiAccounting assingment year ii
Accounting assingment year iiNgeam Soly
 
Account's Assignment
Account's AssignmentAccount's Assignment
Account's AssignmentNgeam Soly
 
Chapter5: Usage of Build-In Functions or Methods
Chapter5: Usage of Build-In Functions or MethodsChapter5: Usage of Build-In Functions or Methods
Chapter5: Usage of Build-In Functions or MethodsNgeam Soly
 
Chapter3: fundamental programming
Chapter3: fundamental programmingChapter3: fundamental programming
Chapter3: fundamental programmingNgeam Soly
 

Mais de Ngeam Soly (9)

សន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាម
សន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាមសន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាម
សន្ធិ​សញ្ញា​កំណត់​ព្រំដែន កម្ពុជា-វៀតណាម
 
អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...
អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...
អត្ថបទគោល៖ ការងារ​បោះ​បង្គោល​ខណ្ឌ​សីមា​ព្រំ​ដែន​​គោក និង​​ការ​​កំណត់​ព្រំដែន​...
 
មេរៀនៈ Data Structure and Algorithm in C/C++
មេរៀនៈ Data Structure and Algorithm in C/C++មេរៀនៈ Data Structure and Algorithm in C/C++
មេរៀនៈ Data Structure and Algorithm in C/C++
 
Chapter01 introduction
Chapter01 introductionChapter01 introduction
Chapter01 introduction
 
Slide for presentation
Slide for presentation Slide for presentation
Slide for presentation
 
Accounting assingment year ii
Accounting assingment year iiAccounting assingment year ii
Accounting assingment year ii
 
Account's Assignment
Account's AssignmentAccount's Assignment
Account's Assignment
 
Chapter5: Usage of Build-In Functions or Methods
Chapter5: Usage of Build-In Functions or MethodsChapter5: Usage of Build-In Functions or Methods
Chapter5: Usage of Build-In Functions or Methods
 
Chapter3: fundamental programming
Chapter3: fundamental programmingChapter3: fundamental programming
Chapter3: fundamental programming
 

Último

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Último (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

Advanced C# ADO.NET Database Programming

  • 3. Introduction Before .NET, developers used data access technologies such as ODBC, OLE DB, and ActiveX Data Object (ADO). With the introduction of .NET, Microsoft created a new way to work with data, called ADO.NET. ADO.NET is a set of classes exposing data access services to .NET programmers, providing a rich set of components for creating distributed, data-sharing applications. ADO.NET is an integral part of the .NET Framework and provides access to relational, XML, and application data.
  • 4. Introductions (Cont.) ADO.NET classes are found in System.Data.dll. This technology supports a variety of development needs, including the creation of front-end database clients and middle-tier business objects used by applications, tools, languages, and Internet browsers. Hence, ADO.NET helps connect the UI, or presentation layer, of your application with the data source or database.
  • 5. ADO.NET and .NET Base Class Library A data set (a DataSet object) can hold large amounts of data in the form of tables (DataTable objects), their relationships (DataRelation objects), and constraints (Constraint objects) in an in-memory cache, which can then be exported to an external file or to another data set. Since XML support is integrated into ADO.NET, you can produce XML schemas and transmit and share data using XML documents.
  • 6. ADO.NET and .NET Base Class Library (Cont.)
  • 7. ADO.NET Architecture ADO.NET offers two types of architectural components to build data-centric applications: connected and disconnected. Within Microsoft .NET Framework, ADO.NET is housed in the namespace System.Data (the assembly name is System.Data.dll), so all the classes and functions for connected and disconnected components live in the same namespace. Hence, it is important to add a reference of System.Data to your application irrespective of the connected or disconnected architecture style you have chosen or will choose later.
  • 9. Connected Data Objects ADO.NET’s connected architecture relies on a consistent database connection to access data and perform any operations on the retrieved data. ADO.NET offers the following objects to help you build your application with a connected architecture: • Connection • Command • DataReader
  • 10. Connection Before you can do anything useful with a database, you need to establish a session with the database server. You do this with an object called a connection. Here below are data providers that provided by Microsoft:
  • 11. Connection (Cont.) String connString = string.Empty; connString = “server = sqlexpress; integrated security = true”; // Window Authentication connString = “server = sqlexpress; user id = sa; password = 1234567”; // SQL Authentication SqlConnection conn = new SqlConnection(connString); Conn.Open(); // // Code // Conn.Close();
  • 12. Command Once you’ve established a connection to the database, you want to start interacting with it and getting it doing something useful for you. You may need to retrieve, add, update, or delete some data, or perhaps modify the database in some other way, usually by running a query. Whatever the task, it will inevitably involve a command.
  • 14. Command (Cont.) Commands aren’t much use unless you can execute them, so let’s look at that now. Commands have several different methods for executing SQL. The differences between these methods depend on the results you expect from the SQL. Queries return rows of data (result sets), but the INSERT, UPDATE, and DELETE statements don’t.
  • 15. DataReader A data reader is a fast, unbuffered, forward-only, read-only connected stream that retrieves data on a per- row basis. It reads one row at a time as it loops through a result set. You can’t directly instantiate a data reader; instead, you create one with the ExecuteReader method of a command.
  • 16. DataReader (Cont.) // Connection string String connString = @"server=.sql2012; database=AdventureWorks;Integrated Security=SSPI"; // Query string sql = @"select Name from Production. Product"; // Create connection SqlConnection conn = new SqlConnection(connString); // Open connection conn.Open();
  • 17. DataReader (Cont.) // Create command SqlCommand cmd = new SqlCommand(sql, conn); // Create data reader SqlDataReader rdr = cmd.ExecuteReader(); // Loop through result set while (rdr.Read()) { // Add to listbox - one row at a time lbxProduct.Items.Add(rdr[0]); } // Close data reader rdr.Close(); conn.Close();
  • 18. Disconnected Data Objects ADO.NET’s disconnected architecture offers flexible application design and helps organizations save database connections. Hence, data can be retrieved and then stored locally on the device in the form of a DataSet object. The retrieved DataSet can be modified by users on their local devices such as laptops, handhelds, tablets, and so on, and once that’s done, they can sync the changes into the central data source. Disconnected architecture utilizes expansive resources like Connection in a very optimum way (that is, to open late and close early).
  • 19. Disconnected Data Objects (Cont.) ADO.NET offers the following objects to help you build your application with a disconnected architecture: • DataSet • DataAdapter • DataTable • DataColumn • DataRow
  • 20. DataSet you’ll look at a new object for accessing data, the data set. Unlike data readers; a distinct ADO.NET component used by all data providers. Data sets are completely independent of and can be used either connected to or disconnected from data sources. Their fundamental purpose is to provide a relational view of data stored in an in-memory cache.
  • 22. DataSet vs DataReader If you simply want to read and display data, then you need to use only a data reader, as you saw in the previous chapter, particularly if you’re working with large quantities of data. In situations where you need to loop through thousands or millions of rows, you want a fast sequential reader (reading rows from the result set one at a time), and the data reader does this job in an efficient way.
  • 23. DataSet vs DataReader (Cont.) If you need to manipulate the data in any way and then update the database, you need to use a data set. A data adapter fills a data set by using a data reader; additional resources are needed to save data for disconnected use. You need to think about whether you really need a data set; otherwise, you’ll just be wasting resources. Unless you need to update the data source or use other data set features such as reading and writing to XML files, exporting database schemas, and creating XML views of a database, you should use a data reader.
  • 24. DataAdapter When you first instantiate a data set, it contains no data. You obtain a populated data set by passing it to a data adapter, which takes care of connection details and is a component of a data provider. A data set isn’t part of a data provider. It’s like a bucket, ready to be filled with water, but it needs an external pipe to let the water in. In other words, the data set needs a data adapter to populate it with data and to support access to the data source. Each data provider has its own data adapter in the same way that it has its own connection, command, and data reader.
  • 26. DataAdapter (Cont.) The data adapter constructor is overloaded. You can use any of the following to get a new data adapter. We’re using the SQL Server data provider, but the constructors for the other data providers are analogous. SqlDataAdapter da = new SqlDataAdapter(); SqlDataAdapter da = new SqlDataAdapter(cmd); SqlDataAdapter da = new SqlDataAdapter(sql, conn); SqlDataAdapter da = new SqlDataAdapter(sql, connString);
  • 27. DataAdapter (Cont.) So, you can create a data adapter in four ways: • You can use its parameterless constructor (assigning SQL and the connection later). • You can pass its constructor a command (here, cmd is a SqlCommand object). • You can pass a SQL string and a connection. • You can pass a SQL string and a connection string.
  • 28. DataSet with DataAdapter // Connection string string connString = @"server=sqlexpress; database=AdventureWorks; Integrated Security=true"; // Query string sql = @"select Name,ProductNumber from Production.Product where SafetyStockLevel > 600"; // Create connection SqlConnection conn = new SqlConnection(connString); // Open connection conn.Open();
  • 29. DataSet with DataAdapter (Cont.) // Create Data Adapter SqlDataAdapter da = new SqlDataAdapter(sql, conn); // Create Dataset DataSet ds = new DataSet(); // Fill Dataset da.Fill(ds, "Production.Product"); // Display data gvProduct.DataSource = ds.Tables["Production.Product"]; //Connection close conn.Close();
  • 30. DataTable A data table is an instance of the class System.Data.DataTable. It’s conceptually analogous to a relational table. You can access these nested collections via the Rows and Columns properties of the data table. A data table can represent a stand-alone independent table, either inside a data set, as you’ll see in this chapter, or as an object created by another method, as you saw in the previous chapter when a data table was returned by calling the GetSchemaTable method on a data reader.
  • 31. DataTable (Cont.) DataTable table = new DataTable("ParentTable"); DataColumn column; DataRow row; column = new DataColumn(); column.DataType = System.Type.GetType("System.Int32"); column.ColumnName = "id"; column.ReadOnly = true; column.Unique = true; table.Columns.Add(column);
  • 32. DataTable (Cont.) column = new DataColumn(); column.DataType = System.Type.GetType("System.String"); column.ColumnName = "ParentItem"; column.AutoIncrement = false; column.Caption = "ParentItem"; column.ReadOnly = false; column.Unique = false; table.Columns.Add(column); DataColumn[] PrimaryKeyColumns = new DataColumn[1]; PrimaryKeyColumns[0] = table.Columns["id"]; table.PrimaryKey = PrimaryKeyColumns;
  • 33. DataTable (Cont.) dataSet = new DataSet(); dataSet.Tables.Add(table); for (int i = 0; i<= 2; i++) { row = table.NewRow(); row["id"] = i; row["ParentItem"] = "ParentItem " + i; table.Rows.Add(row); }
  • 34. DataColumn A data column represents the schema of a column within a data table and can then be used to set or get column properties. For example, you could use it to set the default value of a column by assigning a value to the DefaultValue property of the data column. You obtain the collection of data columns using the data table’s Columns property, whose indexer accepts either a column name or a zero-based index, for example (where dt is a data table): DataColumn col = dt.Columns["ContactName"]; DataColumn col = dt.Columns[2];
  • 35. DataRow A data row represents the data in a row. You can programmatically add, update, or delete rows in a data table. To access rows in a data table, you use its Rows property, whose indexer accepts a zero-based index, for example (where dt is a data table): DataRow row = dt.Rows[2];
  • 36. Understanding .NET Data Providers ADO.NET consists of various data providers that allow an easy and predefined object model to communicate with various industry databases such as SQL Server, Oracle, Microsoft Access, and many others.
  • 37. Understanding .NET Data Providers For example, if you use SQL Server, you should use the SQL Server data provider (System.Data.SqlClient) because it’s the most efficient way to access SQL Server. The OLE DB data provider supports access to older versions of SQL Server as well as to other databases, such as Access, DB2, MySQL, and Oracle. However, native data providers (such as System.Data.OracleClient) are preferable for performance, since the OLE DB data provider works through two other layers, the OLE DB service component and the OLE DB provider, before reaching the data source.
  • 39. Understanding .NET Data Providers Each .NET data provider is designed to do the following two things very well: • Provide access to data with an active connection to the data source • Provide data transmission to and from disconnected data sets and data tables
  • 40. Understanding .NET Data Providers Database connections are established by using the data provider’s Connection class (for example, System.Data.SqlClient.SqlConnection). Other components such as data readers, commands, and data adapters support retrieving data, executing SQL statements, and reading or writing to data sets or data tables, respectively.
  • 41. Understanding the SQL Server Data Provider The .NET data provider for SQL Server is in the System.Data.SqlClient namespace. Although you can use System.Data.OleDb to connect with SQL Server, Microsoft has specifically designed the System.Data.SqlClient namespace to be used with SQL Server, and it works in a more efficient and optimized way than System.Data.OleDb. The reason for this efficiency and optimized approach is that this data provider communicates directly with the server using its native network protocol instead of through multiple layers.
  • 43. Understanding the OLE DB Data Provider • Outside .NET, OLE DB is still Microsoft’s high- performance data access technology. • You can use this data provider to access data stored in any format, so even in ADO.NET it plays an important role in accessing data sources that don’t have their own ADO.NET data providers.
  • 45. Understanding the ODBC Data Provider • ODBC was Microsoft’s original general-purpose data access technology. • The ODBC architecture is essentially a three-tier process. An application uses ODBC functions to submit database requests. ODBC converts the function calls to the protocol (call-level interface) of a driver specific to a given data source. The driver communicates with the data source, passing any results or errors back up to ODBC. Obviously, this is less efficient than a database- specific data provider’s direct communication with a database, so for performance it’s preferable to avoid the ODBC data provider, since it merely offers a simpler interface to ODBC but still involves all the ODBC overhead.
  • 47. Summary This chapter you will understand about two main types of data access that provided from ADO.NET; Connected Data Objects and Disconnected Data Objects. Both types have their own advantages to fulfill the full- functionality to access data. Both types their own main components. • Connected Data Objects : Connection, Command, and DataReader. • Disconnected Data Objects : DataSet, DataAdapter, DataTable, DataColumn and DataRow.