You are on page 1of 46

Data Management

ADO.NET

Technology Solutions Lab

Confidential and Proprietary

Agenda

Introduction to ADO.NET
Programming with ADO.NET
DAAB
Session Summary

Technology Solutions Lab

Confidential and Proprietary

Introduction to ADO.NET
What is ADO.NET?

Natural Evolution of ADO


Interoperability
Based on standards like XML, XSD

Scalability
Targets distributed, disconnected web scenarios

High-performance design
Optimized providers and Objects

Technology Solutions Lab

Confidential and Proprietary

Introduction to ADO.NET
ADO ADO .NET

RecordSet

DataReader
DataAdapter
DataSet

Command

Command

Connection

Connection

Technology Solutions Lab

Confidential and Proprietary

Introduction to ADO.NET
ADO.NET and the .NET Framework

Microsoft .NET Framework

Web Services

User Interface

Data and XML


ADO.NET

XML

...

...

Base Classes
Common Language Runtime

Technology Solutions Lab

Confidential and Proprietary

Introduction to ADO.NET
Managed Data Overview

Controls,
Designers,
Code-gen, etc
DataSet

DataAdapter

Sync

DataReader

Command
Connection

Managed Provider
Technology Solutions Lab

XSL/T, X-Path,
Validation, etc

XmlDataDocument

XmlReader
XmlText- XmlNodeReader
Reader

Confidential and Proprietary

Introduction to ADO.NET
ADO.NET in action

Windows Forms

DataSet

Business Tier

Web Forms

Internet
Intranet
DataSet

XML

Data Object (Class)


DataSet

Data Tier
Data Adapter
Data Adapter

Business to Business

(BizTalk, for example)


Technology Solutions Lab

Confidential and Proprietary

Introduction to ADO.NET
Namespace Organization

System.Data.SqlClient. Contains the SQL Server


.NET Data Provider types.

System.Data.OracleClient. Contains the Oracle


.NET Data Provider types

System.Data.OleDb. Contains the OLE DB .NET


Data Provider types.

System.Data.Odbc. Contains the ODBC .NET Data


Provider types.

System.Data. Contains provider-independent types


such as the DataSet and DataTable.

Technology Solutions Lab

Confidential and Proprietary

Introduction to ADO.NET
Data access stack

Technology Solutions Lab

Confidential and Proprietary

Agenda

Introduction to ADO.NET
Programming with ADO.NET
DAAB
Session Summary

Technology Solutions Lab

Confidential and Proprietary

10

Programming with ADO.NET


Managed Data Providers

ADO.NET relies on the services of .NET

data providers
SQL Server .NET Data Provider
Oracle .NET Data Provider
OLE DB .NET Data Provider
ODBC .NET Data Provider
Managed provider for retrieving XML from SQL Server

2000 (refer:http://msdn.microsoft.com/library/default.asp?
url=/nhp/default.asp?contentid=28001300)

NET Data Provider Object Model


Connection
Command
DataReader :Like a recordset but Forward only and read only
DataAdapter: Transfers data between Database and Dataset
Technology Solutions Lab

Confidential and Proprietary

11

Programming with ADO.NET


Connection

Represents A Connection To The Data


Source
On A Connection, You Can
Represent a unique session with a data source
Create, open, close a connection to a data source
ChangeDatabase, Connection pooling

Create a Command object associated with the


connection

CreateCommand

Begin, commit, and abort transactions

Equivalent To The ADODB.Connection


Object

Technology Solutions Lab

Confidential and Proprietary

12

Programming with ADO.NET


Connection

Example:
//Specify the System.Data.SQL Namespace
//using System.Data.SqlClient
//Create an instance of an SqlConnection object
SqlConnection cnn = new SqlConnection();
//Set the connection string
cnn.ConnectionString = "Data Source=.;Initial
Catalog=Northwind;Integrated Security=SSPI";
//Open the Connection
cnn.Open();

Technology Solutions Lab

Confidential and Proprietary

13

Programming with ADO.NET


Connection

Connection Pooling Example:

IDbConnection conn = new SqlConnection();


conn.ConnectionString = Integrated Security=SSPI; Initial
Catalog=Northwind
conn.Open(); // Pool A is created;
IDbConnection conn = new SqlConnection();
conn.ConnectionString = Integrated Security=SSPI; Initial
Catalog=pubs
conn.Open(); // Pool B is created because connection
string is different
IDbConnection conn = new SqlConnection();
conn.ConnectionString = Integrated Security=SSPI; Initial
Catalog=Northwind
conn.Open(); // Uses Pool A

Technology Solutions Lab

Confidential and Proprietary

14

Programming with ADO.NET


Command

Represents a query to execute on the data

source
May be a SQL statement or stored procedure
Properties of Interest:
Connection: Get or set the data source connection
CommandText: Get or set the query (text)
command

A SQL statement or the name of the stored procedure

CommandType: Get/set how the


command is interpreted

Text, StoredProcedure, or TableDirect


Note: TableDirect is only supported by the .NET
Framework Data Provider for OLE DB.

CommandTimeout: The seconds until


connection timeout

Technology Solutions Lab

Confidential and Proprietary

15

Programming with ADO.NET


DataReader

Forward-only data access


Lightweight programming model
Less overhead than using DataAdapter

Instantiated & returned by

Command.ExecuteReader
Ties up the Command until it is finished reading
Allows Strongly-Typed Access
Example: GetDateTime, GetDouble, GetGuid, GetInt32
Properties of Interest:
FieldCount: Returns the number of fields in the result set
RecordsAffected: Number of affected records

Is not set until all rows are read and you close the
DataReader
The number of rows changed, inserted, or deleted; 0 if no
rows were affected or the statement failed; and -1 for
SELECT statements.
IsClosed and RecordsAffected are the only properties that
you can call after the DataReader is closed.

Technology Solutions Lab

Confidential and Proprietary

16

Programming with ADO.NET


DataReader

Methods to retrieve data:

By column type and/or index: GetValue; GetString; etc.


Read(): Advances reader to next record
NextResult(): Advanced to next result set in batch
GetValues(): Gets the current row

Technology Solutions Lab

Confidential and Proprietary

17

Programming with ADO.NET


DataReader: Example

// Code for creating the OleDbConnection adoConn not shown


String myQuery = SELECT * FROM Customers;
adoConn.Open();
OleDbCommand myCmd = new OleDbCommand( myQuery,adoConn );
// Declare the OleDbDataReader &
// then instantiate it with ExecuteReader(...) ...
OleDbDataReader reader = myCmd.ExecuteReader();
// Always call Read before accessing data.
while( reader.Read() )
{
Object [] cols = new Object[10] ;
reader.GetValues( cols );
Console.WriteLine( cols[0].ToString() + " | " + cols[1] );
}
// Always Close the reader and the connection when done
reader.Close();
adoConn.Close();

Technology Solutions Lab

Confidential and Proprietary

18

Programming with ADO.NET


DataAdapter

Bridge between the DataSet and the data store


Means to modify the DataSet and data source
DataAdapter
Data store

SelectCommand
InsertCommand
UpdateCommand
DeleteCommand

DataSet

TableMappings
Technology Solutions Lab

Confidential and Proprietary

19

Programming with ADO.NET


DataAdapter

RowUpdated, RowUpdating event handlers


ptovides facility to access the row before
updating and after updating
MissingMappingAction
Determines the action to take when incoming

data does not have a matching table or column


Passthrough, Ignore, Error

MissingSchemaAction

Determines the action to take when existing

DataSet schema does not match incoming data.


Add, AddWithKey, Ignore, Error

Technology Solutions Lab

Confidential and Proprietary

20

Programming with ADO.NET


DataSet

In memory store for client


data
Relational view of data
Tables, Columns, Rows
Constraints, Relations

DataSet
Tables
Table
Columns
Column

Persist Data And Schema


As XML
Explicit Disconnected
Model

Constraints
Constraint
Rows
Row

Disconnected, remotable object


Relations
Relation

Technology Solutions Lab

Confidential and Proprietary

21

Programming with ADO.NET


DataSet

DataSet

Tables
DataTable

DataView

DataRow(s)

Relations
DataRelation
DataRelation

DataColumn
Constraint(s)

DataViewManager

DataTable
DataTable

Technology Solutions Lab

Confidential and Proprietary

22

Programming with ADO.NET


DataSet Life cycle
Connected
Operations

DataSet
Table1

Extracts tables
With Managed
Provider

Original
DataStore

Table2

Disconnected
Operations
Resolves changes

Sets up
relationships

with Managed
Provider

DataSet
DataSet
Table1

Table1

Makes changes
to data
Table2
Table2

Technology Solutions Lab

Confidential and Proprietary

23

Programming with ADO.NET


DataSet DataTable

May be mapped to a physical table in the

data source
Can be related to one another through
DataRelations
Optimistic concurrency or locking - model
Properties of Interest:
Columns: Returns ColumnsCollection of DataColumns
Rows: Returns DataRow objects as a RowsCollection
ParentRelations: Returns the RelationsCollection
Constraints: Returns the tables

ConstraintsCollection
DataSet: Returns the DataSet of the DataTable
PrimaryKey: Gets the DataColumns that make up
the tables primary key

Technology Solutions Lab

Confidential and Proprietary

24

Programming with ADO.NET


DataSet DataTable Example

Create a DataTable and add it to a


DataSet
ds = new DataSet();
DataSet

// Create DataTable object: Customers.


DataTable dt= new DataTable( Customers );
// Create and add columns to the table
// 1. Explicitly create and Add a DataColumn
DataColumn dc;
dc = new DataColumn( CustID, Type.GetType("System.Int16"));
dt.Columns.Add( dc );
// 2. Implicitly Create and Add columns (DataColumn).
dt.Columns.Add( First_Name,Type.GetType("System String));
dt.Columns.Add( Last_Name, Type.GetType("System String));
// Add the DataTable object to the DataSet
ds.Tables.Add( dt );

Technology Solutions Lab

Confidential and Proprietary

25

Programming with ADO.NET

DataSet Optimistic concurrency Example

SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial


Catalog=northwind");
SqlDataAdapter custDA = new SqlDataAdapter("SELECT CustomerID, CompanyName FROM Customers ORDER BY
CustomerID", nwindConn);
// The Update command checks for optimistic concurrency violations in the WHERE clause.
custDA.UpdateCommand = new SqlCommand("UPDATE Customers (CustomerID, CompanyName) VALUES(@CustomerID,
@CompanyName) " +
"WHERE CustomerID = @oldCustomerID AND CompanyName = @oldCompanyName", nwindConn);
custDA.UpdateCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
custDA.UpdateCommand.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 30, "CompanyName");
// Pass the original values to the WHERE clause parameters.
SqlParameter myParm;
myParm = custDA.UpdateCommand.Parameters.Add("@oldCustomerID", SqlDbType.NChar, 5, "CustomerID");
myParm.SourceVersion = DataRowVersion.Original;
myParm = custDA.UpdateCommand.Parameters.Add("@oldCompanyName", SqlDbType.NVarChar, 30, "CompanyName");
myParm.SourceVersion = DataRowVersion.Original;
// Add the RowUpdated event handler.
custDA.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated);
DataSet custDS = new DataSet();
custDA.Fill(custDS, "Customers");
// Modify the DataSet contents.
custDA.Update(custDS, "Customers");
foreach (DataRow myRow in custDS.Tables["Customers"].Rows)
{
if (myRow.HasErrors)
Console.WriteLine(myRow[0] + "\n" + myRow.RowError);
}
protected static void OnRowUpdated(object sender, SqlRowUpdatedEventArgs args)
{
if (args.RecordsAffected == 0)
{
args.Row.RowError = "Optimistic Concurrency Violation Encountered";
args.Status = UpdateStatus.SkipCurrentRow;
}
}

Technology Solutions Lab

Confidential and Proprietary

26

Programming with ADO.NET

DataSet DataTable Relations:DataRelation object

Used to create logical relations between

your data
Create relations between two (2) DataTable objects
Requires a DataColumn object from each DataTable
The DataType of both DataColumns must be the
same
Cannot relate a Int32 DataColumn and a String
DataColumn
The relation is named (by you!)
DataRelation dr=new DataRelation( myRelation,...)

RelationsCollection used to hold/group

them
Accessed through the DataSets Relations property

Technology Solutions Lab

Confidential and Proprietary

27

Programming with ADO.NET

DataSet DataTable Relations:DataRelation object

Example
// Building on the DataTable example earlier...
// Get the DataTable DataColumns we want to relate...
DataColumn parentCol, childCol;
parentCol=
DataSet.Tables["Customers"].Columns["CustID"];
childCol = DataSet.Tables["Orders].Columns["CustID"];
// Create DataRelation with the name CustomerOrders...
DataRelation dr = new DataRelation("CustomersOrders",
parentCol,
childCol);
// Add the relation to the DataSet...
ds.Relations.Add( dr );

Technology Solutions Lab

Confidential and Proprietary

28

Programming with ADO.NET


DataSet and XML

DataSet can read/write XML for its data and/or


schema

You can create or modify data in a DataSet using XML


You can create or modify the DataSets schema using XML

XML-related DataSet methods for reading:

ReadXml: Reads an XML schema and data into the DataSet


ReadXmlSchema: Reads an XML schema into the DataSet

And for writing:

WriteXml, WriteXmlSchema
GetXml, GetXmlSchema

Namespace property:

The Namespace property is used when reading and writing


an XML document into the DataSet

Full support for DiffGrams

A DiffGram is an XML format that is used to identify


current and original versions of data elements

Technology Solutions Lab

Confidential and Proprietary

29

Programming with ADO.NET


DataSet and XML: Example

// Code for creating the DataSet mds and loading the


// DataSet from a data source not shown.
String oFile = C:\\My_ADO.NET\\myXmlOutput.xsd;
String iFile = C:\\My_ADO.NET\\myXmlInput.xml;
// Write the DataSets XMLSchema to an XML Document
mds.WriteXmlSchema( oFile );
// Read/Upload XML Data into the DataSet
mds.ReadXml( iFile);
// modify the data
// ...
// Write the existing Data to an XML Document
mds.WriteXml( "C:\\My_ADO.NET\\myXmlData.xml",
XmlWriteMode.DiffGram);

Technology Solutions Lab

Confidential and Proprietary

30

Programming with ADO.NET


DataSet and XmlDataDocument

Exposes relational view over structured


XML
Allows strong typing, control binding,
relational access of XML data
Allows XML tools (schema validation,
XSL/T, XPath queries) against relational
data
Preserves full fidelity of XML Document

Technology Solutions Lab

Confidential and Proprietary

31

Programming with ADO.NET


DataSet and XmlDataDocument

Technology Solutions Lab

Confidential and Proprietary

32

Programming with ADO.NET

DataSet and XmlDataDocument : Example

// Associate an XmlDataDocument with the DataSet


XmlDataDocument xmlDocument = new XmlDataDocument(pubs);
// Get an XmlNavigator for the XmlDataDocument
DataDocumentNavigator xmlNavigator = new
DataDocumentNavigator(xmlDocument);
// Get all the authors from CA
xmlNavigator.Select("//Authors[state='CA']/au_lname");
// Write out all of the authors' last names
while(xmlNavigator.MoveToNextSelected())
{
Console.WriteLine("Name = " + xmlNavigator.InnerText);
}
//As usual, you can navigate the data using the DataSet
DataRow row;
foreach(row in xmlDocument .DataSet.Tables[0].Rows)
{
Console.WriteLine(row[1]) ; //prints au_lname
}

Technology Solutions Lab

Confidential and Proprietary

33

Programming with ADO.NET

DataSet and XmlDataDocument : Example

Populate DataSet with XML Document


DataSet RegionDS = new DataSet();

RegionDS.ReadXmlSchema( "Region_More.XSD" );

XmlDataDocument DataDoc = new


XmlDataDocument( RegionDS );

DataDoc.Load("Region_More.XML" );
//Now RegionDS contains data loaded from XML file

Technology Solutions Lab

Confidential and Proprietary

34

Programming with ADO.NET


DataViews

DataSet

Tables
DataTable

Relations
DataRelation
DataRelation

DataView

DataRow(s)

DataViewManag
er

DataColumn

DataViewSettings

Constraint(s)

DataViewSetting
DataViewSetting

DataTable
DataTable

Technology Solutions Lab

Confidential and Proprietary

35

Programming with ADO.NET


DataViews: Viewing Data

Create multiple views on DataTable objects


Bindable to user interface controls
Properties of Interest:
Table: Retrieves or sets the associated DataTable
Sort: Gets or sets the tables sort columns and sort

order
RowFilter: Gets or sets the expression used to filter
rows
RowStateFilter: Gets or sets the row state filter
None, Unchanged, New, Deleted, ModifiedCurrent, and
others

Technology Solutions Lab

Confidential and Proprietary

36

Programming with ADO.NET


DataViews: Viewing Data: Example

// Code for myTable Customers with Name column not


shown
DataView view1 = new DataView( myTable );
DataView view2 = new DataView( myTable );
// Creates Ascending view of Customers by Name
view1.Sort = Name ASC;
// Set the view to show only modified (original) rows
view2.RowStateFilter=
DataViewRowState.ModifiedOriginal;
// Bind to UI element(s)...
DataGrid myGrid = new DataGrid();
myGrid.SetDataBinding( view1, Customer);
//...

Technology Solutions Lab

Confidential and Proprietary

37

Programming with ADO.NET

DataViews: Viewing More Data : DataViewManager

Similar to a DataView but DataSet oriented


Used to create multiple views on a DataSet
Ability to automatically set filters on the tables
Properties of Interest:
DataViewSettings: Gets the DataView for on each
DataTable
DataSet: Gets or sets the DataSet to be viewed

CreateDataView method
Creates a DataView on a DataTable

Technology Solutions Lab

Confidential and Proprietary

38

Programming with ADO.NET

DataViews: DataViewManager : Example

// Create the DataViewManager & views...


DataViewManager dvMgr = new DataViewManager( myDS );
dvMgr.CreateDataView( ds.Tables[Orders"] );
dvMgr.DataViewSettings[Orders"].Sort = CustID ASC";
dvMgr.CreateDataView( ds.Tables[Customers"] );
dvMgr.DataViewSettings[Customers"].Sort = Name DESC";
// Bind to a UI elements/controls...
dataGrid1.DataSource = viewMgr;
dataGrid1.DataMember = "Table1";
dataGrid2.DataSource = viewMgr;
dataGrid2.DataMember = "Table2";
// Update the control with the data...
dataGrid1.Update();
dataGrid2.Update();

Technology Solutions Lab

Confidential and Proprietary

39

Programming with ADO.NET


Paging: Examples

1. adpter.Fill(ds,startrecord, maxrecords,sourceTableName)
2. switch (direction) //Next, Previous
{
case "Next":
selCmd.CommandText = "SELECT TOP " + pageSize + " CustomerID, CompanyName FROM
Customers " +
"WHERE CustomerID > @CustomerId ORDER BY CustomerID";
selCmd.Parameters.Add("@CustomerId", SqlDbType.VarChar, 5).Value = lastVisibleCustomer;
break;
case "Previous":
selCmd.CommandText = "SELECT TOP " + pageSize + " CustomerID, CompanyName FROM
Customers " +
"WHERE CustomerID < @CustomerId ORDER BY CustomerID DESC";
selCmd.Parameters.Add("@CustomerId", SqlDbType.VarChar, 5).Value = firstVisibleCustomer;
break;
default:
selCmd.CommandText = "SELECT TOP " + pageSize + " CustomerID, CompanyName FROM
Customers ORDER BY CustomerID";
// Determine total pages.
SqlCommand totCMD = new SqlCommand("SELECT Count(*) FROM Customers", nwindConn);
nwindConn.Open();
int totalRecords = (int)totCMD.ExecuteScalar();
nwindConn.Close();
totalPages = (int)Math.Ceiling((double)totalRecords / pageSize);
break;
}

Technology Solutions Lab

Confidential and Proprietary

40

Agenda

Introduction to ADO.NET
Programming with ADO.NET
DAAB
Session Summary

Technology Solutions Lab

Confidential and Proprietary

41

DAAB

Technology Solutions Lab

Confidential and Proprietary

42

DAAB
SqlHelper class

provides a set of static methods that you can use to

execute a variety of different command types against


a SQL Server database.

SqlHelperParameterCache class

provides command parameter caching functionality

used to improve performance. This is used internally


by a number of the Execute methods (specifically, the
overloads that are designed to execute only stored
procedures). It can also be used directly by the data
access client to cache specific parameter sets for
specific commands.
Uses sp_procedure_params_rowset procedure

URL: http://msdn.microsoft.com/library/default.asp?
url=/library/en-us/dnbda/html/daab-rm.asp

Technology Solutions Lab

Confidential and Proprietary

43

Agenda

Introduction to ADO.NET
Programming with ADO.NET
DAAB
Session Summary

Technology Solutions Lab

Confidential and Proprietary

44

Session Summary

Bflex applications Architecture Overview


User / Browser

ASP.NET

IIS
Web

EAF

DataAccess
DAL1
DAAB

Base Components

BusinessRules

ADO.NET
Database
Technology Solutions Lab

Confidential and Proprietary

45

Session Summary

A natural evolution of ADO


Designed to work with XML
Closely integrated with the .NET

Framework
Provides fast and efficient mechanisms for
connected and disconnected data access

Technology Solutions Lab

Confidential and Proprietary

46

You might also like