SlideShare a Scribd company logo
1 of 32
Download to read offline
ADO.NET

Dietrich Birngruber


Software Architect
TechTalk
www.techtalk.at
Contents

    Part I: Basics
    Part II: Connection-Oriented Scenario
    Part III: Disconnected Scenario
    Part IV: Data Access Layer Sample




ADO.NET, Dietrich Birngruber, TechTalk      2
Motivation

    How to access different data sources?
     – „back office“, OO/RDBMS, files, (web-)server, ...


               Application           Oracle
               (object-oriented) implementation 1            Oracle

                                              IBM
                                         implementation 2   IBM Host
     Application
     (object-oriented)                    ??? data access
                                         implementation 3     ???

    Is there a unified programming model and API available ?

ADO.NET, Dietrich Birngruber, TechTalk                                 3
Microsoft Data Access Components

                                   (.NET) Applications

                              ADO.NET

 data source                                            OLEDB
  specific
              ODBC

         SQL data                        Non SQL data            Mainframe and
  MS SQL Server, Oracle,            Directory services,
                                                                other proprietary
  DB2, Jet, ...                     email, text files, ...        data sources

ADO.NET, Dietrich Birngruber, TechTalk                                              4
Architectural Overview

                                                                                      .NET data
                                              .NET Application                          types

           data




                                                                                     SQL commands
                                      DataSet                IDataReader
ADO.NET




           consumer




                                                                                                    data
                                                   IDbCommand
           data
           provider          SqlCommand OleDbCommand XYCommand*

                            MsSQL Server                        Proprietary access   data types of
                                                     OLEDB
                               specific                           protocol XY          the data
                             Data Source (SQL Server, XML files, …)                     source

                                                                           * ODBC, Oracle (v1.1)
          ADO.NET, Dietrich Birngruber, TechTalk                                                           5
Connection Oriented Scenario

    Connection to data source remains alive
    IDataReader for reading

    Scenarios with …
     – low number of concurrent accesses
     – short running transactions
     – data always up to date


                         Data access        data
                            logic          source
                        Application
ADO.NET, Dietrich Birngruber, TechTalk              6
Disconnected Scenario

    No permanent connection to the data source
    Data is cached in DataSet
    Modifications in DataSet ≠ modifications in the data source


    Scenarios with …
     – a lot of concurrent, long running read accesses (e.g. web)



               (Read)             DataSet       data
               Access             (Buffer)     source
                      Application
ADO.NET, Dietrich Birngruber, TechTalk                              7
Namespaces (System.Data.dll)

    System.Data                  (basic types)
    System.Data.OleDb             (OLEDB provider)
    System.Data.SqlClient (Microsoft SQL Server provider)
    System.Data.Common
    System.Data.SqlTypes
    System.Data.Odbc                      (ODBC provider, since .NET 1.1)
    System.Data.OracleClient              (Oracle provider, since .NET 1.1)
    System.Data.SqlServerCe               (Compact Framework)


    Extra download (prior to NET1.1):
     – Microsoft.Data.Odbc
     – System.Data.OracleClient

ADO.NET, Dietrich Birngruber, TechTalk                                        8
Contents

    Part I: Basics
    Part II: Connection-Oriented Scenario
    Part III: Disconnected Scenario
    Part IV: Data Access Layer Sample




ADO.NET, Dietrich Birngruber, TechTalk      9
Example: Northwind

      Food & beverages merchant
     –    Microsoft sample; part of MSDE (MS SQL Server)
      Task: read table „Employees“
      Steps:
     1. Connect to database
        (IDbConnection)
     2. Execute SQL command object
        (IDbCommand)
     3. Read and compute
        (IDataReader)
     4. Release resources


ADO.NET, Dietrich Birngruber, TechTalk                     10
Typical Program Structure

using System.Data;
....
1.) Declare connection;
try { // optional
  1.) Create connection to data source;
  2.) Execute SQL commands;
  3.) Compute result;
  4.) Release resources;
} catch ( Exception ) {
  Handle exception or dispatch it;
} finally {
  try { // optional
      4.) Close connection;
    } catch (Exception) { Handle exception; }
}


ADO.NET, Dietrich Birngruber, TechTalk          11
Code: EmployeeReader
   using System;
   using System.Data;
   using System.Data.OleDb;

   public class EmployeeReader {
    public static void Main() {
     //----- Connect to local data base
     string connStr = "provider=SQLOLEDB; data source=(local)NetSDK; " +
                       "initial catalog=Northwind; user id=sa; password=; ";
     IDbConnection con = null; // declare connection variable
     try {
      con = new OleDbConnection(connStr);
1.) con.Open(); //open connection
      //----- Create command object and define SQL command text
      IDbCommand cmd = con.CreateCommand(); //creates an OleDbCommand object
      cmd.CommandText = "SELECT EmployeeID, LastName, FirstName FROM Employees";

       //next slide ...




   ADO.NET, Dietrich Birngruber, TechTalk                                     12
Code: EmployeeReader (2)

             //....
             //----- execute command object; it returns an OleDbDataReader
             IDataReader reader = cmd.ExecuteReader();
2.)          object[] dataRow = new object[reader.FieldCount];
             //----- read data row by row ... forward only cursor
             while (reader.Read()) {
3.)           int cols = reader.GetValues(dataRow);
              for (int i = 0; i < cols; i++) Console.Write("| {0} " , dataRow[i]);
              Console.WriteLine();
             }
             //----- close reader and release resources
             reader.Close();
4.)         } catch (Exception e) {
             Console.WriteLine(e.Message);
            } finally {
             try {
              if (con != null)
4.)              con.Close(); // ALWAYS close a connection!
             } catch (Exception ex) { Console.WriteLine(ex.Message); }
            }
        }
      }
      ADO.NET, Dietrich Birngruber, TechTalk                                         13
IDbConnection Interface

For creating a connection to a data source (see step 1. )...

public interface IDbConnection : IDisposable {
   //----- properties
   string ConnectionString {get; set;}
   int ConnectionTimeout {get;}
   ...
   //----- methods
   IDbTransaction BeginTransaction();
   IDbTransaction BeginTransaction(IsolationLevel lvl);
   void Close();
   void Open();
   IDbCommand CreateCommand();
   ...
}


ADO.NET, Dietrich Birngruber, TechTalk                         14
ConnectionString Property

    Configures the connection
    Semicolon separated list of key – value pairs
    E.g. OLEDB:
      "provider=SQLOLEDB; data source=127.0.0.1NetSDK;
       initial catalog=Northwind; user id=sa; password=; "
      "provider=Microsoft.Jet.OLEDB.4.0;data source=c:binLocalAccess40.mdb;"
      "provider=MSDAORA; data source=ORACLE8i7; user id=OLEDB;
       password=OLEDB;"
    E.g. MS SQL Server:
      "data source=(local)NetSDK; initial catalog=Northwind; user id=sa;
       pooling=false; Integrated Security=SSPI; connection timout=20;"



ADO.NET, Dietrich Birngruber, TechTalk                                       15
“Execute” Methods of IDbCommand Interface


For executing SQL commands (see step 2. ) …


    IDataReader ExecuteReader(...)
     – Property CommandText only contains SQL SELECT statements

    int ExecuteNonQuery()
     – Property CommandText contains INSERT, UPDATE, DELETE, ...
         cmd.CommandText = "UPDATE Empls SET City = ’Seattle’ WHERE lD=8";
         int affectedRows = cmd.ExecuteNonQuery();




ADO.NET, Dietrich Birngruber, TechTalk                                   16
“Execute” Methods of IDbCommand Interface


    object ExecuteScalar()
     – Property CommandText contains SQL aggregate functions
         IDbCommand cmd = new SqlCommand("SELECT count(*) FROM Empls",
                                                new SqlConnection(connStr));
         cmd.Connection.Open();
         int count = (int) cmd.ExecuteScalar();
         cmd.Connection.Close();




ADO.NET, Dietrich Birngruber, TechTalk                                   17
How To: Parameters And SQL Commands

1.    Define formal parameters
     //here we use OLEDB
     OleDbCommand cmd = new OleDbCommand();
     cmd.CommandText = "DELETE FROM Empls WHERE EmployeeID = ?";
     cmd.Parameters.Add(new OleDbParameter("anID", OleDbType.BigInt));
     cmd.Connection = ...



2.    Assign actual parameters and execute command
     cmd.Parameters["anID"].Value = 1234; // or cmd.Parameters[0]
     cmd.ExecuteNonQuery();




ADO.NET, Dietrich Birngruber, TechTalk                               18
Contents

    Part I: Basics
    Part II: Connection-Oriented Scenario
    Part III: Disconnected Scenario
    Part IV: Data Access Layer Sample




ADO.NET, Dietrich Birngruber, TechTalk      19
Support for a Disconnected Scenario

    For distributed (enterprise) applications
     – A lot of concurrent read accesses
     – Designed for an n-tier client/server architecture in mind
     – E.g.: web shop, product catalog
    DataSet caches data
     – Database “snapshot" in memory
     – In memory representation of an XML data and schema
    DataSet is independent of a data source
     – Location, including multiple data sources (database, XML file, …)
    DataSet is used in .NET framework
     – ASP.NET, Web Services, Win Forms, ...
    DataAdapter is used for synchronization with data sources

ADO.NET, Dietrich Birngruber, TechTalk                                 20
N-Tier Client/Server Architecture

   Presentation Logic                          Business Logic           Data Logic
Client Side         Server Side


                     Web                    Business components &
                  components                  OO Domain Model
 Web
browser           ASP.NET,                          Business logic
                 .NET classes                        components
                  Web server
                                           Web      Domain model
                                         service     components
                                          facade                           Data




                                                                 .NET
                                                                 ADO
                                                   Data access
  Smart                                                                   sources
                                                   components
 Clients
                                           Web & application server       (remote)
                                                                           access
ADO.NET, Dietrich Birngruber, TechTalk                                               21
Zoom In: N-Tier Client/Server Architecture
               Business Logic / Data Access Logic                                                                       Data
                                                                                                                       Sources
DataSet                                              DataAdapter




                                                                                              IDataReade r
                                                                          IDbTransactio n, IDb Co nnection
 DataTableCollection                          Fill   SelectCommand                                           select     Database
                 DataRowCollection                     ParameterColl.
  DataTable
                 DataColumnCollection
   „Person“                                          InsertCommand                                            insert
                 ConstraintCollection
  DataTable                                            ParameterColl.                                                    Person
                                            Update
  „Contact“                                          UpdateCommand                                           update      Contact
                                                      ParameterColl.
 DataRelationCollection
                                                     DeleteCommand                                           delete
                                                      ParameterColl.
                     ReadXml
                     WriteXml

                                                        Data flow, disconnected scenario

                                                         Data flow, connected scenario
               XML file

   ADO.NET, Dietrich Birngruber, TechTalk                                                                                     22
New Data Types

DataSet
                    DataTable
                    DataTable                      Schema
.Tables[...]
                    .Columns[..]
                     .Columns[...]       DataColumn DataColumn

                     .Rows[...]
                    .Rows[..]            DataRow
                                                                 Data
                                         DataRow

                     .DefaultView        DataView
                     ...
.Relations[...]
                        DataRelation
                        DataRelation
...
ADO.NET, Dietrich Birngruber, TechTalk                                  23
Example: Contacts

            Concept                                              Implementation

 Person                 Contact                 DataTable „Person“                            DataTable „Contact“
ID                     ID                      DataColumn „ID“                                DataColumn „ID“




                                                                        „PersonHasContacts“
FirstName              FirstName               DataColumn „FirstName“                         DataColumn „FirstName“




                                                                            DataRelation
Name                   Name                    DataColumn „Name“                              DataColumn „Name“

                       NickName                                                               DataColumn „NickName“

                       EMail                                                                  DataColumn „EMail“

                       Phone                                                                  DataColumn „Phone“

                       PersonID               DataSet                                         DataColumn „PersonID“



         TODO: to read data and fill a DataSet
         We need a DbDataAdapter or an IDbDataAdapter
          – E.g.: OleDbDataAdapter, SqlDataAdapter, ...
     ADO.NET, Dietrich Birngruber, TechTalk                                                                        24
Beispiel: Kontaktliste (2)

DataSet LoadData() {
 //----- define SELECT commands
 OleDbCommand cmd = new OleDbCommand();
 cmd.Connection = new OleDbConnection ("provider=SQLOLEDB; " +
 " data source=(local)NetSDK; database=netbook; user id=sa; password=;" );
 cmd.CommandText = "SELECT * FROM Person; SELECT * FROM Contact";

  DataSet ds = new DataSet("PersonContacts");
  IDbDataAdapter adapter = new OleDbDataAdapter();
  adapter.SelectCommand = cmd;
  //----- DataSet is empty and contains no DataTable objects
  adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
  //----- Rename automatically created DataTable objects
  adapter.TableMappings.Add("Table", "Person");
  adapter.TableMappings.Add("Table1", "Contact");
  //----- Read data and populate the DataSet
  adapter.Fill(ds);


ADO.NET, Dietrich Birngruber, TechTalk                                         25
Beispiel: Kontaktliste (3)

    if (ds.HasErrors) {
       ds.RejectChanges();
    } else {
       DefineRelation(ds); //... or read schema information from the data source
       ds.AcceptChanges();
    }
    if (adapter is IDisposable) ((IDisposable)adapter).Dispose();
    return ds;
}

void DefineRelation(DataSet ds) {
  DataColumn parentCol = ds.Tables["Person"].Columns["ID"];
  DataColumn childCol = ds.Tables["Contact"].Columns["PersonID"];
  DataRelation rel = new DataRelation("PersonHasContacts",
                                            parentCol, childCol);
  ds.Relations.Add(rel);
}


ADO.NET, Dietrich Birngruber, TechTalk                                             26
Contents

    Part I: Basics
    Part II: Connection-Oriented Scenario
    Part III: Disconnected Scenario
    Part IV: Data Access Layer Sample




ADO.NET, Dietrich Birngruber, TechTalk      27
Example: Data Access Layer

    Mismatch: object-oriented world vs. relational World
     – Objects, classes, inheritance, object graph, life-time, …
     – Row, tables, relation, constraints, joins, …
    Goal: Mapping OO – relational world
     – Reusable domain model (classes)
     – Transparent persistency mechanism
    Tool for developer
    Object Query Language
     – Set oriented and NO tables!
     – “Class” == type + all objects
    Used in .NET projects at TechTalk
ADO.NET, Dietrich Birngruber, TechTalk                             28
Usage Scenario

1.   Design and implement object-oriented domain model
     –    Abstract classes, separate assembly (DLL)


2.   Define mapping rules in XML file
     –    Classes of the domain model    tables in the relational data base


3.   Generate separate mapping assembly (DLL) with a tool
     –    Uses ADO.NET and contains SQL commands


4.   Test and use generated files
     –    With a tool and in your code

ADO.NET, Dietrich Birngruber, TechTalk                                        29
Supported OO-Relational Mapping Strategies

                                           OO        Relational
    Root Inheritance
     – NO hierarchy                        Class A   A1 | A2
                                                     „1“ | „2“
     – Only objects of type „A“
    Shared Inheritance
     – All instances in one table          Class A   A1 | A2 | B1 | TID
     – Type discriminator                            „1“| „2“|null|    A
                                           Class B   „1“| „4“| „3“ |    B
     – null values in DB,
         but fast read access
    Joined Inheritance
                                           Class A   A1 | A2 | ID      B1| A_ID
     – 1 type == 1 table
                                                     „1“| „2“| A1      „3“| A2
     – Hierarchy == relation (SQL joins)   Class B   „1“| „4“| A2



ADO.NET, Dietrich Birngruber, TechTalk                                       30
Summary

    Connection-oriented scenario
     – Always current data
     – Low number of concurrent data accesses
     – Many write access situations
     – IDbConnection, IDbCommand, IDataReader
    Disconnected scenario
     – Modifications in DataSet ≠ modifications in the data source
     – Many concurrent read access situations
     – DataSet, DataTable, DbDataAdapter
    DAL example
     – Generative programming approach
     – Bridges the gap between OO world and relational world
ADO.NET, Dietrich Birngruber, TechTalk                               31
Questions + Contact

http://dotnet.jku.at
http://www.ssw.uni-linz.ac.at
http://www.techtalk.at


birngruber@acm.org




ADO.NET, Dietrich Birngruber, TechTalk   32

More Related Content

What's hot

Setting up your virtual infrastructure using fi lab cloud
Setting up your virtual infrastructure using fi lab cloudSetting up your virtual infrastructure using fi lab cloud
Setting up your virtual infrastructure using fi lab cloud
Henar Muñoz Frutos
 

What's hot (20)

Igor Kochetov "What is wrong with Dependency Injection? Myths and Truths"
Igor Kochetov "What is wrong with Dependency Injection? Myths and Truths"Igor Kochetov "What is wrong with Dependency Injection? Myths and Truths"
Igor Kochetov "What is wrong with Dependency Injection? Myths and Truths"
 
What’s New in Spring Batch?
What’s New in Spring Batch?What’s New in Spring Batch?
What’s New in Spring Batch?
 
Serhiy Kalinets "Building Service Mesh with .NET Core"
Serhiy Kalinets "Building Service Mesh with .NET Core"Serhiy Kalinets "Building Service Mesh with .NET Core"
Serhiy Kalinets "Building Service Mesh with .NET Core"
 
Micro Frontends
Micro FrontendsMicro Frontends
Micro Frontends
 
"Dynamic configuration in .NET", Serhii Buta
"Dynamic configuration in .NET", Serhii Buta"Dynamic configuration in .NET", Serhii Buta
"Dynamic configuration in .NET", Serhii Buta
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
 
Spring Security Patterns
Spring Security PatternsSpring Security Patterns
Spring Security Patterns
 
SIngle Sign On with Keycloak
SIngle Sign On with KeycloakSIngle Sign On with Keycloak
SIngle Sign On with Keycloak
 
Context Information Management in IoT enabled smart systems - the basics
Context Information Management in IoT enabled smart systems - the basicsContext Information Management in IoT enabled smart systems - the basics
Context Information Management in IoT enabled smart systems - the basics
 
What's new in c# 10
What's new in c# 10What's new in c# 10
What's new in c# 10
 
CIS13: OpenStack API Security
CIS13: OpenStack API SecurityCIS13: OpenStack API Security
CIS13: OpenStack API Security
 
Winning the Lottery with Spring: A Microservices Case Study for the Dutch Lot...
Winning the Lottery with Spring: A Microservices Case Study for the Dutch Lot...Winning the Lottery with Spring: A Microservices Case Study for the Dutch Lot...
Winning the Lottery with Spring: A Microservices Case Study for the Dutch Lot...
 
Setting up your virtual infrastructure using fi lab cloud
Setting up your virtual infrastructure using fi lab cloudSetting up your virtual infrastructure using fi lab cloud
Setting up your virtual infrastructure using fi lab cloud
 
Overview of Microsoft .Net Remoting technology
Overview of Microsoft .Net Remoting technologyOverview of Microsoft .Net Remoting technology
Overview of Microsoft .Net Remoting technology
 
Flare: an overview
Flare: an overviewFlare: an overview
Flare: an overview
 
Security Patterns for Microservice Architectures - SpringOne 2020
Security Patterns for Microservice Architectures - SpringOne 2020Security Patterns for Microservice Architectures - SpringOne 2020
Security Patterns for Microservice Architectures - SpringOne 2020
 
ASP.NET MVC Workshop for Women in Technology
ASP.NET MVC Workshop for Women in TechnologyASP.NET MVC Workshop for Women in Technology
ASP.NET MVC Workshop for Women in Technology
 
Implementing Microservices Security Patterns & Protocols with Spring
Implementing Microservices Security Patterns & Protocols with SpringImplementing Microservices Security Patterns & Protocols with Spring
Implementing Microservices Security Patterns & Protocols with Spring
 
Understanding MicroSERVICE Architecture with Java & Spring Boot
Understanding MicroSERVICE Architecture with Java & Spring BootUnderstanding MicroSERVICE Architecture with Java & Spring Boot
Understanding MicroSERVICE Architecture with Java & Spring Boot
 

Similar to 5c8605.ado.net

What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?
ukdpe
 
Data Access Technologies
Data Access TechnologiesData Access Technologies
Data Access Technologies
Dimara Hakim
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
Doncho Minkov
 
Sql Injection and Entity Frameworks
Sql Injection and Entity FrameworksSql Injection and Entity Frameworks
Sql Injection and Entity Frameworks
Rich Helton
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
Madhuri Kavade
 
Yogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’sYogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’s
Yogesh Kushwah
 
Ado.net session05
Ado.net session05Ado.net session05
Ado.net session05
Niit Care
 
Ado.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworksAdo.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworks
Luis Goldster
 
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
Amandeep Kaur
 

Similar to 5c8605.ado.net (20)

Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2
 
What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?
 
Entity Framework V1 and V2
Entity Framework V1 and V2Entity Framework V1 and V2
Entity Framework V1 and V2
 
ADO.NET Data Services &amp; Entity Framework
ADO.NET Data Services &amp; Entity FrameworkADO.NET Data Services &amp; Entity Framework
ADO.NET Data Services &amp; Entity Framework
 
Ado.net
Ado.netAdo.net
Ado.net
 
Marmagna desai
Marmagna desaiMarmagna desai
Marmagna desai
 
Data Access Technologies
Data Access TechnologiesData Access Technologies
Data Access Technologies
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
 
Sql Injection and Entity Frameworks
Sql Injection and Entity FrameworksSql Injection and Entity Frameworks
Sql Injection and Entity Frameworks
 
Introduction To Dot Net Siddhesh
Introduction To Dot Net SiddheshIntroduction To Dot Net Siddhesh
Introduction To Dot Net Siddhesh
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
5.C#
5.C#5.C#
5.C#
 
Yogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’sYogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’s
 
Microsoft data access components
Microsoft data access componentsMicrosoft data access components
Microsoft data access components
 
Lecture17
Lecture17Lecture17
Lecture17
 
Ado.net session05
Ado.net session05Ado.net session05
Ado.net session05
 
Ado.Net
Ado.NetAdo.Net
Ado.Net
 
Ado.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworksAdo.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworks
 
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
 

More from harkesh singh

5b9b046 sample interviewquestionbook(1)
5b9b046 sample interviewquestionbook(1)5b9b046 sample interviewquestionbook(1)
5b9b046 sample interviewquestionbook(1)
harkesh singh
 
5a329780735625624 ch10
5a329780735625624 ch105a329780735625624 ch10
5a329780735625624 ch10
harkesh singh
 
5b9b046 sample interviewquestionbook(1)
5b9b046 sample interviewquestionbook(1)5b9b046 sample interviewquestionbook(1)
5b9b046 sample interviewquestionbook(1)
harkesh singh
 
000eworld no tobacco day
000eworld no tobacco day000eworld no tobacco day
000eworld no tobacco day
harkesh singh
 
0a2b animals that_carry_flu
0a2b animals that_carry_flu0a2b animals that_carry_flu
0a2b animals that_carry_flu
harkesh singh
 
3f87 ielts listening
3f87 ielts listening3f87 ielts listening
3f87 ielts listening
harkesh singh
 
22d2 optimal assembly line balancing222
22d2 optimal assembly line balancing22222d2 optimal assembly line balancing222
22d2 optimal assembly line balancing222
harkesh singh
 
Fc30 nano technology
Fc30 nano technologyFc30 nano technology
Fc30 nano technology
harkesh singh
 

More from harkesh singh (12)

5b9b046 sample interviewquestionbook(1)
5b9b046 sample interviewquestionbook(1)5b9b046 sample interviewquestionbook(1)
5b9b046 sample interviewquestionbook(1)
 
5a329780735625624 ch10
5a329780735625624 ch105a329780735625624 ch10
5a329780735625624 ch10
 
5b9b046 sample interviewquestionbook(1)
5b9b046 sample interviewquestionbook(1)5b9b046 sample interviewquestionbook(1)
5b9b046 sample interviewquestionbook(1)
 
34d7 android
34d7 android34d7 android
34d7 android
 
000eworld no tobacco day
000eworld no tobacco day000eworld no tobacco day
000eworld no tobacco day
 
0a2b animals that_carry_flu
0a2b animals that_carry_flu0a2b animals that_carry_flu
0a2b animals that_carry_flu
 
3f87 ielts listening
3f87 ielts listening3f87 ielts listening
3f87 ielts listening
 
22d2 optimal assembly line balancing222
22d2 optimal assembly line balancing22222d2 optimal assembly line balancing222
22d2 optimal assembly line balancing222
 
4f94ny mortgage 2
4f94ny mortgage 24f94ny mortgage 2
4f94ny mortgage 2
 
C953ny mortgage 3
C953ny mortgage 3C953ny mortgage 3
C953ny mortgage 3
 
Fc30 nano technology
Fc30 nano technologyFc30 nano technology
Fc30 nano technology
 
Ba20 boyaca rhea46
Ba20 boyaca rhea46Ba20 boyaca rhea46
Ba20 boyaca rhea46
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Recently uploaded (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

5c8605.ado.net

  • 2. Contents Part I: Basics Part II: Connection-Oriented Scenario Part III: Disconnected Scenario Part IV: Data Access Layer Sample ADO.NET, Dietrich Birngruber, TechTalk 2
  • 3. Motivation How to access different data sources? – „back office“, OO/RDBMS, files, (web-)server, ... Application Oracle (object-oriented) implementation 1 Oracle IBM implementation 2 IBM Host Application (object-oriented) ??? data access implementation 3 ??? Is there a unified programming model and API available ? ADO.NET, Dietrich Birngruber, TechTalk 3
  • 4. Microsoft Data Access Components (.NET) Applications ADO.NET data source OLEDB specific ODBC SQL data Non SQL data Mainframe and MS SQL Server, Oracle, Directory services, other proprietary DB2, Jet, ... email, text files, ... data sources ADO.NET, Dietrich Birngruber, TechTalk 4
  • 5. Architectural Overview .NET data .NET Application types data SQL commands DataSet IDataReader ADO.NET consumer data IDbCommand data provider SqlCommand OleDbCommand XYCommand* MsSQL Server Proprietary access data types of OLEDB specific protocol XY the data Data Source (SQL Server, XML files, …) source * ODBC, Oracle (v1.1) ADO.NET, Dietrich Birngruber, TechTalk 5
  • 6. Connection Oriented Scenario Connection to data source remains alive IDataReader for reading Scenarios with … – low number of concurrent accesses – short running transactions – data always up to date Data access data logic source Application ADO.NET, Dietrich Birngruber, TechTalk 6
  • 7. Disconnected Scenario No permanent connection to the data source Data is cached in DataSet Modifications in DataSet ≠ modifications in the data source Scenarios with … – a lot of concurrent, long running read accesses (e.g. web) (Read) DataSet data Access (Buffer) source Application ADO.NET, Dietrich Birngruber, TechTalk 7
  • 8. Namespaces (System.Data.dll) System.Data (basic types) System.Data.OleDb (OLEDB provider) System.Data.SqlClient (Microsoft SQL Server provider) System.Data.Common System.Data.SqlTypes System.Data.Odbc (ODBC provider, since .NET 1.1) System.Data.OracleClient (Oracle provider, since .NET 1.1) System.Data.SqlServerCe (Compact Framework) Extra download (prior to NET1.1): – Microsoft.Data.Odbc – System.Data.OracleClient ADO.NET, Dietrich Birngruber, TechTalk 8
  • 9. Contents Part I: Basics Part II: Connection-Oriented Scenario Part III: Disconnected Scenario Part IV: Data Access Layer Sample ADO.NET, Dietrich Birngruber, TechTalk 9
  • 10. Example: Northwind Food & beverages merchant – Microsoft sample; part of MSDE (MS SQL Server) Task: read table „Employees“ Steps: 1. Connect to database (IDbConnection) 2. Execute SQL command object (IDbCommand) 3. Read and compute (IDataReader) 4. Release resources ADO.NET, Dietrich Birngruber, TechTalk 10
  • 11. Typical Program Structure using System.Data; .... 1.) Declare connection; try { // optional 1.) Create connection to data source; 2.) Execute SQL commands; 3.) Compute result; 4.) Release resources; } catch ( Exception ) { Handle exception or dispatch it; } finally { try { // optional 4.) Close connection; } catch (Exception) { Handle exception; } } ADO.NET, Dietrich Birngruber, TechTalk 11
  • 12. Code: EmployeeReader using System; using System.Data; using System.Data.OleDb; public class EmployeeReader { public static void Main() { //----- Connect to local data base string connStr = "provider=SQLOLEDB; data source=(local)NetSDK; " + "initial catalog=Northwind; user id=sa; password=; "; IDbConnection con = null; // declare connection variable try { con = new OleDbConnection(connStr); 1.) con.Open(); //open connection //----- Create command object and define SQL command text IDbCommand cmd = con.CreateCommand(); //creates an OleDbCommand object cmd.CommandText = "SELECT EmployeeID, LastName, FirstName FROM Employees"; //next slide ... ADO.NET, Dietrich Birngruber, TechTalk 12
  • 13. Code: EmployeeReader (2) //.... //----- execute command object; it returns an OleDbDataReader IDataReader reader = cmd.ExecuteReader(); 2.) object[] dataRow = new object[reader.FieldCount]; //----- read data row by row ... forward only cursor while (reader.Read()) { 3.) int cols = reader.GetValues(dataRow); for (int i = 0; i < cols; i++) Console.Write("| {0} " , dataRow[i]); Console.WriteLine(); } //----- close reader and release resources reader.Close(); 4.) } catch (Exception e) { Console.WriteLine(e.Message); } finally { try { if (con != null) 4.) con.Close(); // ALWAYS close a connection! } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } ADO.NET, Dietrich Birngruber, TechTalk 13
  • 14. IDbConnection Interface For creating a connection to a data source (see step 1. )... public interface IDbConnection : IDisposable { //----- properties string ConnectionString {get; set;} int ConnectionTimeout {get;} ... //----- methods IDbTransaction BeginTransaction(); IDbTransaction BeginTransaction(IsolationLevel lvl); void Close(); void Open(); IDbCommand CreateCommand(); ... } ADO.NET, Dietrich Birngruber, TechTalk 14
  • 15. ConnectionString Property Configures the connection Semicolon separated list of key – value pairs E.g. OLEDB: "provider=SQLOLEDB; data source=127.0.0.1NetSDK; initial catalog=Northwind; user id=sa; password=; " "provider=Microsoft.Jet.OLEDB.4.0;data source=c:binLocalAccess40.mdb;" "provider=MSDAORA; data source=ORACLE8i7; user id=OLEDB; password=OLEDB;" E.g. MS SQL Server: "data source=(local)NetSDK; initial catalog=Northwind; user id=sa; pooling=false; Integrated Security=SSPI; connection timout=20;" ADO.NET, Dietrich Birngruber, TechTalk 15
  • 16. “Execute” Methods of IDbCommand Interface For executing SQL commands (see step 2. ) … IDataReader ExecuteReader(...) – Property CommandText only contains SQL SELECT statements int ExecuteNonQuery() – Property CommandText contains INSERT, UPDATE, DELETE, ... cmd.CommandText = "UPDATE Empls SET City = ’Seattle’ WHERE lD=8"; int affectedRows = cmd.ExecuteNonQuery(); ADO.NET, Dietrich Birngruber, TechTalk 16
  • 17. “Execute” Methods of IDbCommand Interface object ExecuteScalar() – Property CommandText contains SQL aggregate functions IDbCommand cmd = new SqlCommand("SELECT count(*) FROM Empls", new SqlConnection(connStr)); cmd.Connection.Open(); int count = (int) cmd.ExecuteScalar(); cmd.Connection.Close(); ADO.NET, Dietrich Birngruber, TechTalk 17
  • 18. How To: Parameters And SQL Commands 1. Define formal parameters //here we use OLEDB OleDbCommand cmd = new OleDbCommand(); cmd.CommandText = "DELETE FROM Empls WHERE EmployeeID = ?"; cmd.Parameters.Add(new OleDbParameter("anID", OleDbType.BigInt)); cmd.Connection = ... 2. Assign actual parameters and execute command cmd.Parameters["anID"].Value = 1234; // or cmd.Parameters[0] cmd.ExecuteNonQuery(); ADO.NET, Dietrich Birngruber, TechTalk 18
  • 19. Contents Part I: Basics Part II: Connection-Oriented Scenario Part III: Disconnected Scenario Part IV: Data Access Layer Sample ADO.NET, Dietrich Birngruber, TechTalk 19
  • 20. Support for a Disconnected Scenario For distributed (enterprise) applications – A lot of concurrent read accesses – Designed for an n-tier client/server architecture in mind – E.g.: web shop, product catalog DataSet caches data – Database “snapshot" in memory – In memory representation of an XML data and schema DataSet is independent of a data source – Location, including multiple data sources (database, XML file, …) DataSet is used in .NET framework – ASP.NET, Web Services, Win Forms, ... DataAdapter is used for synchronization with data sources ADO.NET, Dietrich Birngruber, TechTalk 20
  • 21. N-Tier Client/Server Architecture Presentation Logic Business Logic Data Logic Client Side Server Side Web Business components & components OO Domain Model Web browser ASP.NET, Business logic .NET classes components Web server Web Domain model service components facade Data .NET ADO Data access Smart sources components Clients Web & application server (remote) access ADO.NET, Dietrich Birngruber, TechTalk 21
  • 22. Zoom In: N-Tier Client/Server Architecture Business Logic / Data Access Logic Data Sources DataSet DataAdapter IDataReade r IDbTransactio n, IDb Co nnection DataTableCollection Fill SelectCommand select Database DataRowCollection ParameterColl. DataTable DataColumnCollection „Person“ InsertCommand insert ConstraintCollection DataTable ParameterColl. Person Update „Contact“ UpdateCommand update Contact ParameterColl. DataRelationCollection DeleteCommand delete ParameterColl. ReadXml WriteXml Data flow, disconnected scenario Data flow, connected scenario XML file ADO.NET, Dietrich Birngruber, TechTalk 22
  • 23. New Data Types DataSet DataTable DataTable Schema .Tables[...] .Columns[..] .Columns[...] DataColumn DataColumn .Rows[...] .Rows[..] DataRow Data DataRow .DefaultView DataView ... .Relations[...] DataRelation DataRelation ... ADO.NET, Dietrich Birngruber, TechTalk 23
  • 24. Example: Contacts Concept Implementation Person Contact DataTable „Person“ DataTable „Contact“ ID ID DataColumn „ID“ DataColumn „ID“ „PersonHasContacts“ FirstName FirstName DataColumn „FirstName“ DataColumn „FirstName“ DataRelation Name Name DataColumn „Name“ DataColumn „Name“ NickName DataColumn „NickName“ EMail DataColumn „EMail“ Phone DataColumn „Phone“ PersonID DataSet DataColumn „PersonID“ TODO: to read data and fill a DataSet We need a DbDataAdapter or an IDbDataAdapter – E.g.: OleDbDataAdapter, SqlDataAdapter, ... ADO.NET, Dietrich Birngruber, TechTalk 24
  • 25. Beispiel: Kontaktliste (2) DataSet LoadData() { //----- define SELECT commands OleDbCommand cmd = new OleDbCommand(); cmd.Connection = new OleDbConnection ("provider=SQLOLEDB; " + " data source=(local)NetSDK; database=netbook; user id=sa; password=;" ); cmd.CommandText = "SELECT * FROM Person; SELECT * FROM Contact"; DataSet ds = new DataSet("PersonContacts"); IDbDataAdapter adapter = new OleDbDataAdapter(); adapter.SelectCommand = cmd; //----- DataSet is empty and contains no DataTable objects adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; //----- Rename automatically created DataTable objects adapter.TableMappings.Add("Table", "Person"); adapter.TableMappings.Add("Table1", "Contact"); //----- Read data and populate the DataSet adapter.Fill(ds); ADO.NET, Dietrich Birngruber, TechTalk 25
  • 26. Beispiel: Kontaktliste (3) if (ds.HasErrors) { ds.RejectChanges(); } else { DefineRelation(ds); //... or read schema information from the data source ds.AcceptChanges(); } if (adapter is IDisposable) ((IDisposable)adapter).Dispose(); return ds; } void DefineRelation(DataSet ds) { DataColumn parentCol = ds.Tables["Person"].Columns["ID"]; DataColumn childCol = ds.Tables["Contact"].Columns["PersonID"]; DataRelation rel = new DataRelation("PersonHasContacts", parentCol, childCol); ds.Relations.Add(rel); } ADO.NET, Dietrich Birngruber, TechTalk 26
  • 27. Contents Part I: Basics Part II: Connection-Oriented Scenario Part III: Disconnected Scenario Part IV: Data Access Layer Sample ADO.NET, Dietrich Birngruber, TechTalk 27
  • 28. Example: Data Access Layer Mismatch: object-oriented world vs. relational World – Objects, classes, inheritance, object graph, life-time, … – Row, tables, relation, constraints, joins, … Goal: Mapping OO – relational world – Reusable domain model (classes) – Transparent persistency mechanism Tool for developer Object Query Language – Set oriented and NO tables! – “Class” == type + all objects Used in .NET projects at TechTalk ADO.NET, Dietrich Birngruber, TechTalk 28
  • 29. Usage Scenario 1. Design and implement object-oriented domain model – Abstract classes, separate assembly (DLL) 2. Define mapping rules in XML file – Classes of the domain model tables in the relational data base 3. Generate separate mapping assembly (DLL) with a tool – Uses ADO.NET and contains SQL commands 4. Test and use generated files – With a tool and in your code ADO.NET, Dietrich Birngruber, TechTalk 29
  • 30. Supported OO-Relational Mapping Strategies OO Relational Root Inheritance – NO hierarchy Class A A1 | A2 „1“ | „2“ – Only objects of type „A“ Shared Inheritance – All instances in one table Class A A1 | A2 | B1 | TID – Type discriminator „1“| „2“|null| A Class B „1“| „4“| „3“ | B – null values in DB, but fast read access Joined Inheritance Class A A1 | A2 | ID B1| A_ID – 1 type == 1 table „1“| „2“| A1 „3“| A2 – Hierarchy == relation (SQL joins) Class B „1“| „4“| A2 ADO.NET, Dietrich Birngruber, TechTalk 30
  • 31. Summary Connection-oriented scenario – Always current data – Low number of concurrent data accesses – Many write access situations – IDbConnection, IDbCommand, IDataReader Disconnected scenario – Modifications in DataSet ≠ modifications in the data source – Many concurrent read access situations – DataSet, DataTable, DbDataAdapter DAL example – Generative programming approach – Bridges the gap between OO world and relational world ADO.NET, Dietrich Birngruber, TechTalk 31