Module 8: Using

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 36

Module 8: Using

ADO.NET
Overview

 ADO.NET Overview
 .NET Data Providers
 The DataSet Object
 Data Designers and Data Binding
 XML Integration
 ADO.NET Overview

 Introduction to ADO.NET
 Benefits of ADO.NET
Introduction to ADO.NET

ASP.NET Windows Forms

Class Framework

Drawing XML Data


Data ADO.NET

Common Language Runtime

System Services
Benefits of ADO.NET

 Similar to ADO
 Designed for disconnected data
 Intrinsic to the .NET Framework
 Supports XML
 .NET Data Providers

 Using the Connection Object


 Using the Command Object
 Using the Command Object with Stored Procedures
 Using the DataReader Object
 Using the DataAdapter Object
Using the Connection Object

 Connecting from a Web application


 Add a line to Web.config file
<identity
<identity impersonate="true"
impersonate="true" userName="Karen"
userName="Karen"
password="Password"/>
password="Password"/>

 SqlConnection
Dim
Dim conSQL
conSQL As
As New
New SqlClient.SqlConnection(
SqlClient.SqlConnection( ))
conSQL.ConnectionString
conSQL.ConnectionString == "Integrated
"Integrated Security=True;"
Security=True;" && __
"Data
"Data Source=LocalHost;Initial
Source=LocalHost;Initial Catalog=Pubs;"
Catalog=Pubs;"
conSQL.Open(
conSQL.Open( ))
Using the Command Object

 Two ways to create a  Four ways to execute a


Command: Command:
 Command constructor  ExecuteReader
 CreateCommand  ExecuteScalar
method
 ExecuteNonQuery
 ExecuteXMLReader
Dim
Dim commSQL
commSQL As
As New
New SqlClient.SqlCommand(
SqlClient.SqlCommand( ))
commSQL.Connection
commSQL.Connection == conSQL
conSQL
commSQL.CommandText
commSQL.CommandText == "Select
"Select Count(*)
Count(*) from
from Authors"
Authors"
MessageBox.Show(commSQL.ExecuteScalar(
MessageBox.Show(commSQL.ExecuteScalar( ).ToString)
).ToString)
Using the Command Object with Stored Procedures

1. Create a Command object


2. Set the CommandType to StoredProcedure
3. Set the CommandText property
4. Use the Add method to create and set parameters
5. Use the ParameterDirection property
6. Call ExecuteReader
7. Use records, and then close DataReader
8. Access output and return parameters
Using the DataReader Object

 Reading data
Dim
Dim commSQL
commSQL AsAs New
New SqlClient.SqlCommand(
SqlClient.SqlCommand( ))
commSQL.Connection
commSQL.Connection == conSQL
conSQL
commSQL.CommandText
commSQL.CommandText ="Select
="Select au_lname,au_fname
au_lname,au_fname from
from authors"
authors"
Dim datRead As SqlClient.SqlDataReader
Dim datRead As SqlClient.SqlDataReader
datRead
datRead == commSQL.ExecuteReader(
commSQL.ExecuteReader( ))
Do
Do Until
Until datRead.Read
datRead.Read == False
False
MessageBox.Show(datRead.GetString(1)
MessageBox.Show(datRead.GetString(1) && "" "" __
&& datRead.GetString(0))
datRead.GetString(0))
Loop
Loop
datRead.Close(
datRead.Close( ))

 Retrieving data
 Returning multiple result sets
Using the DataAdapter Object

 Used as a link between data source and cached tables

Dim
Dim adaptSQL
adaptSQL As
As New
New SqlClient.SqlDataAdapter(
SqlClient.SqlDataAdapter( __
"Select
"Select ** from
from authors",
authors", conSQL)
conSQL)

Dim
Dim datPubs
datPubs As
As New
New DataSet(
DataSet( ))
adaptSQL.Fill(datPubs,
adaptSQL.Fill(datPubs, "NewTable")
"NewTable")

'' Manipulate
Manipulate the
the data
data locally
locally

adaptSQL.Update
adaptSQL.Update (datPubs,
(datPubs, "NewTable")
"NewTable")
Demonstration: Retrieving Data Using ADO.NET
 The DataSet Object

 Disconnected Data Review


 The DataSet Object
 Populating DataSets
 Using Relationships in DataSets
 Using Constraints
 Updating Data in the DataSet
 Updating Data at the Source
Disconnected Data Review

DAO
Connected environment

RDO
Disconnected environment

ADO
Connected and
disconnected environments
COM Marshalling

ADO.NET
Disconnected architecture
XML format
The DataSet Object

DataSet Object

Collection
Tables Table

Columns Column

Constraints Constraint

Rows Row

Relations Relation
Populating DataSets

 Populating DataSets from an RDBMS


Dim
Dim adaptSQL
adaptSQL As
As New
New SqlClient.SqlDataAdapter(
SqlClient.SqlDataAdapter( __
"Select
"Select ** from
from authors",
authors", conSQL)
conSQL)

Dim
Dim datPubs
datPubs As
As DataSet
DataSet == New
New DataSet(
DataSet( ))
adaptSQL.Fill(datPubs,
adaptSQL.Fill(datPubs, "NewTable")
"NewTable")

 Programmatically creating DataSets


Dim
Dim datPubs
datPubs As
As New
New DataSet(
DataSet( ))
Dim
Dim tblAuthors
tblAuthors AsAs DataTable
DataTable == New
New DataTable("authors")
DataTable("authors")
tblAuthors.Columns.Add("AuthorID",
tblAuthors.Columns.Add("AuthorID", System.Type.GetType
System.Type.GetType __
("System.Int32"))
("System.Int32"))
Using Relationships in DataSets

 Creating relationships
Dim
Dim relPubsTitle
relPubsTitle As
As New
New DataRelation("PubsTitles",
DataRelation("PubsTitles", __
datPubs.Tables("Publishers").Columns("pub_id"),
datPubs.Tables("Publishers").Columns("pub_id"), __
datPubs.Tables("Titles").Columns("pub_id"))
datPubs.Tables("Titles").Columns("pub_id"))
datPubs.Relations.Add(relPubsTitle)
datPubs.Relations.Add(relPubsTitle)

 Accessing related data


Dim
Dim PubRow,
PubRow, TitleRow
TitleRow As
As DataRow,
DataRow, TitleRows(
TitleRows( )) As
As DataRow
DataRow

PubRow
PubRow == datPubs.Tables("Publishers").Rows(0)
datPubs.Tables("Publishers").Rows(0)
TitleRows
TitleRows == PubRow.GetChildRows("PubsTitles")
PubRow.GetChildRows("PubsTitles")
Using Constraints

 Creating new constraints


 ForeignKeyConstraints
 UniqueConstraints
 Using existing constraints
adaptSQL
adaptSQL == New
New SqlClient.SqlDataAdapter("Select
SqlClient.SqlDataAdapter("Select title_id"
title_id" __
&& ",
", title,
title, type,
type, price
price from
from titles",
titles", conSQL)
conSQL)
adaptSQL.FillSchema(datPubs,
adaptSQL.FillSchema(datPubs, schematype.Source,
schematype.Source, "Titles")
"Titles")
adaptSQL.Fill(datPubs,
adaptSQL.Fill(datPubs, "Titles")
"Titles")
'Edit some data
'Edit some data
adaptSQL.Fill(datPubs,
adaptSQL.Fill(datPubs, "Titles")
"Titles")
Updating Data in the DataSet

 Adding rows
Dim
Dim drNewRow
drNewRow As
As DataRow
DataRow == datPubs.Tables("Titles").NewRow
datPubs.Tables("Titles").NewRow
'Populate
'Populate columns
columns
datPubs.Tables("Titles").Rows.Add(drNewRow)
datPubs.Tables("Titles").Rows.Add(drNewRow)
 Editing rows
drChangeRow.BeginEdit(
drChangeRow.BeginEdit( ))
drChangeRow("Title")
drChangeRow("Title") == drChangeRow("Title").ToString
drChangeRow("Title").ToString && "" 1"
1"
drChangeRow.EndEdit(
drChangeRow.EndEdit( ))

 Deleting data
datPubs.Tables("Titles").Rows.Remove(drDelRow)
datPubs.Tables("Titles").Rows.Remove(drDelRow)
Updating Data at the Source

 Explicitly specifying the updates


Dim
Dim comm
comm As
As New
New SqlClient.SqlCommand("Insert
SqlClient.SqlCommand("Insert titles"
titles" && __
"(title_id,
"(title_id, title,
title, type)
type) values(@t_id,@title,@type)")
values(@t_id,@title,@type)")
comm.Parameters.Add("@t_id",SqlDbType.VarChar,6,"title_id")
comm.Parameters.Add("@t_id",SqlDbType.VarChar,6,"title_id")
comm.Parameters.Add("@title",SqlDbType.VarChar,80,"title")
comm.Parameters.Add("@title",SqlDbType.VarChar,80,"title")
comm.Parameters.Add("@type",SqlDbType.Char,12,"type")
comm.Parameters.Add("@type",SqlDbType.Char,12,"type")
adaptSQL.InsertCommand
adaptSQL.InsertCommand == commcomm
adaptSQL.Update(datPubs,
adaptSQL.Update(datPubs, "titles")
"titles")

 Automatically generating the updates


Dim
Dim sqlCommBuild
sqlCommBuild As
As New
New SqlCommandBuilder(adaptSQL)
SqlCommandBuilder(adaptSQL)
MsgBox(sqlCommBuild.GetInsertCommand.CommandText)
MsgBox(sqlCommBuild.GetInsertCommand.CommandText)
adaptSQL.Update(datPubs,
adaptSQL.Update(datPubs, "titles")
"titles")
Practice: Using DataSets
 Data Designers and Data Binding

 Designing DataSets
 Data Form Wizard
 Data Binding in Windows Forms
 Data Binding in Web Forms
Designing DataSets

 DataAdapter Configuration Wizard


 Generates a DataAdapter object in the
InitializeComponent procedure for use in your code
 Generate DataSet Tool
 Generates a DataSet based on data from an existing
DataAdapter
Data Form Wizard

 Information required:
 Name of DataSet
 Connection to be used
 Which tables or views, and which columns within them
 How to display the data
 Which buttons to create
Demonstration: Using the Data Form Wizard
Data Binding in Windows Forms

 Simple binding
da
da == New
New SqlClient.SqlDataAdapter("Select
SqlClient.SqlDataAdapter("Select au_lname,
au_lname, "" && __
"au_fname
"au_fname from
from authors",
authors", sqlconn)
sqlconn)
da.Fill(ds,
da.Fill(ds, "authors")
"authors")
TextBox1.DataBindings.Add("Text",
TextBox1.DataBindings.Add("Text", __
ds.Tables("authors"),
ds.Tables("authors"), "au_fname")
"au_fname")

 Complex binding
da
da == New
New SqlClient.SqlDataAdapter("Select
SqlClient.SqlDataAdapter("Select au_lname,
au_lname, "" && __
"au_fname
"au_fname from
from authors",
authors", sqlconn)
sqlconn)
da.Fill(ds,
da.Fill(ds, "authors")
"authors")
DataGrid1.DataSource
DataGrid1.DataSource == ds.Tables("authors")
ds.Tables("authors")
Data Binding in Web Forms

 Use impersonation
<identity
<identity impersonate="true"
impersonate="true" userName="Karen"
userName="Karen"
password="Password"/>
password="Password"/>

 Binding to read-only data


Dim
Dim sqlComm
sqlComm As
As New
New SqlClient.SqlCommand("Select
SqlClient.SqlCommand("Select ** from
from "" && __
"authors",
"authors", sqlconn)
sqlconn)
Dim
Dim sqlReader
sqlReader As
As SqlClient.SqlDataReader
SqlClient.SqlDataReader
sqlReader = sqlComm.ExecuteReader
sqlReader = sqlComm.ExecuteReader
DataGrid1.DataSource(
DataGrid1.DataSource( )) == sqlReader
sqlReader
DataGrid1.DataBind(
DataGrid1.DataBind( ))
 XML Integration

 Why Use Schemas?


 Describing XML Structure
 Creating Schemas
 Using XML Data and Schemas in ADO.NET
 DataSets and XmlDataDocuments
Why Use Schemas?

 Define format of data


 Use for validity checking
 Advantages over DTDs
 XML syntax
 Reusable types
 Grouping
Describing XML Structure

 Schemas can describe:


 Elements in the document
 Attributes in the document
 Element and attribute relationships
 Data types
 The order of the elements
 Which elements are optional
Creating Schemas

 Creating schemas from existing XML documents


 Creating schemas from databases
 Working with schemas
 Validating XML documents against schemas
Using XML Data and Schemas in ADO.NET

 Loading XML data into a DataSet


Dim
Dim datXML
datXML As
As DataSet
DataSet == New
New DataSet()
DataSet()
datXML.ReadXml("c:\publishers.xml")
datXML.ReadXml("c:\publishers.xml")
MessageBox.Show(datXML.Tables(0).Rows(0)(0).ToString)
MessageBox.Show(datXML.Tables(0).Rows(0)(0).ToString)

 Using a typed DataSet


 Increases performance
 Simplifies coding
MessageBox.Show(pubs.Publishers(0).pub_id)
MessageBox.Show(pubs.Publishers(0).pub_id)
DataSets and XmlDataDocuments

XSLT, XPath, Schema, Controls, Designers,


DTD, etc. Code Generation

sync
XmlDataDocument DataSet

XmlReader XmlReader Managed Provider

XML Documents XML Documents Data Source


Demonstration: Using XML Schemas
Lab 8.1: Creating Applications That Use ADO.NET
Review

 ADO.NET Overview
 .NET Data Providers
 The DataSet Object
 Data Designers and Data Binding
 XML Integration

You might also like