Tải bản đầy đủ - 0 (trang)
Chapter 11: Overview of the ADO.NET Classes

Chapter 11: Overview of the ADO.NET Classes

Tải bản đầy đủ - 0trang

Overview

ADO.NETallowsyoutointeractwithadatabasedirectlyusingobjects

ofthemanagedproviderclasses.Theseobjectsallowyoutoconnect

tothedatabaseandexecuteSQLstatementswhiledirectlyconnected

tothedatabase.ObjectsliketheDataReaderallowyoutoconnectto

adatabasedirectlyandreadtherowsfromatableinaforward-only

direction.

ADO.NETalsoallowsyoutoworkinadisconnectedmanner.When

doingthis,youstoreinformationfromadatabaselocallyinthe

memoryofthecomputeronwhichyourprogramisrunning.Youstore

thatinformationusingobjectsofthedatasetclasses.Onceyouhave

thatinformationinthememory,youcanthenreadandmanipulatethat

information.Forexample,youcandisplaythecolumnsfortherows,

addnewrows,modifyrows,anddeleterows.Periodically,you'll

reconnecttothedatabasetosynchronizeyourchangesyou'vemade

locallywiththedatabase.Thisdisconnectedmodelallowsyoutowrite

applicationsthatrunontheInternet,aswellasfordevicesthataren't

alwaysconnectedtothedatabase—PDAssuchasthePalmandthe

PocketPC,forexample.

ThischapterprovidesdescriptionsoftheADO.NETclasses.Italso

givesyouacompleteC#programthatconnectstoadatabase,stores

therowslocally,disconnectsfromthedatabase,andthenreadsthe

contentsofthoselocalrowswhiledisconnectedfromthedatabase.

Thiscapabilitytostorealocalcopyofrowsretrievedfromthe

databaseisoneofthemainstrengthsofADO.NET.Theexample

programillustratesthebasicideasofusingtheADO.NET

disconnectedmodeltoreadrowsfromthedatabaseandstorethem

locallyinmemory.Inlaterchapters,you'llseehowtomodifydata

locallyandthensynchronizethosechangeswiththedatabase.



TheManagedProviderandGenericDataSet

Classes

Toprovidebothconnectedanddisconnecteddatabaseaccess,

ADO.NETdefinestwosetsofclasses:managedproviderandgeneric

data.

Youuseobjectsofthemanagedproviderclassestodirectlyconnect

toadatabaseandtosynchronizeyourlocallystoreddatawiththe

database.Youcanusethemanagedproviderclassestoreadrows

fromthedatabaseinaforward-onlydirection.Youuseadifferentset

ofmanagedproviderclassesdependingonthedatabaseyouuse.

Youuseobjectsofthegenericdataclassestostorealocalcopyof

theinformationretrievedfromthedatabase.Thiscopyisstoredinthe

memoryofthecomputerwheretheC#programisrunning.Themain

genericdataclassistheSystem.Data.DataSetclass.Thegeneric

dataclasses,astheirnamesuggests,arenotspecifictoany

database,andyoualwaysusethesameclassesregardlessofthe

databaseyouuse.Thegenericdataclassesrepresentinformation

retrievedfromthedatabaseasXML.



TheManagedProviderClasses

Themanagedproviderobjectsallowyoutodirectlyaccessa

database,andyou'llbeintroducedtotheclassesthatallowyouto

createtheseobjectsinthissection.Youusethemanagedprovider

objectstoconnecttothedatabaseandreadandwriteinformationto

andfromthedatabase.

Figure11.1illustratessomeofthemanagedproviderobjectsandhow

theyrelatetoeachother.



Figure11.1:Someofthe

managedproviderobjects

Therearecurrentlythreesetsofmanagedproviderclasses,andeach

setisdesignedtoworkwithdifferentdatabasestandards.Thesethree

setsofclassesallimplementthesamebasicfunctionality.

SQLServerManagedProviderClassesYouusetheSQL

ServermanagedproviderclassestoconnecttoaSQLServer

database.

OLEDBManagedProviderClassesYouusetheOLEDB

(ObjectLinkingandEmbeddingforDatabases)managed

providerclassestoconnecttoanydatabasethatsupportsOLE

DB,suchasAccessorOracle.

ODBCManagedProviderClassesYouusetheODBC(Open

DatabaseConnectivity)managedproviderclassestoconnectto

anydatabasethatsupportsODBC.Allthemajordatabases

supportODBC,butODBCistypicallyslowerthantheprevious

twosetsofclasseswhenworkingwith.NET.Youshouldusethe

ODBCmanagedproviderclassesonlywhentherearen'tany

alternativeOLEDBmanagedproviderclasses.



Note WheneveryouseeSqlatthestartofamanagedprovider

classname,youknowthatclassisusedwithaSQLServer

database.Forexample,SqlConnectionallowsyouto

connecttoaSQLServerdatabase.Similarly,OleDbisfor

databasesthatsupportOLEDB.Forexample,

OleDbConnectionallowsyoutoconnecttoadatabase

usingOLEDB.Finally,Odbcisfordatabasesthatsupport

ODBC.Forexample,OdbcConnectionallowsyouto

connecttoadatabaseusingODBC.Irefertoallofthese

classesastheConnectionclasses.

You'llseesomeofthevariousmanaged-providerclassesinthe

followingsections.



TheConnectionClasses

TherearethreeConnectionclasses:SqlConnection,

OleDbConnection,andOdbcConnection.Youuseanobjectof

theSqlConnectionclasstoconnecttoaSQLServerdatabase.You

useanobjectoftheOleDbConnectionclasstoconnecttoany

databasethatsupportsOLEDB,suchasAccessorOracle.Youuse

anobjectoftheOdbcConnectionclasstoconnecttoanydatabase

thatsupportsODBC.Ultimately,allcommunicationwithadatabaseis

donethroughaConnectionobject.



TheCommandClasses

TherearethreeCommandclasses:SqlCommand,OleDbCommand,

andOdbcCommand.YouuseaCommandobjecttorunaSQL

statement,suchasaSELECT,INSERT,UPDATE,orDELETE

statement.YoucanalsouseaCommandobjecttocallastored

procedureorretrieverowsfromaspecifictable.Yourunthe

commandstoredinaCommandobjectusingaConnectionobject.



TheParameterClasses

TherearethreeParameterclasses:SqlParameter,



OleDbParameter,andOdbcParameter.YouuseaParameter

objecttopassaparametertoaCommandobject.Youcanusea

ParametertopassavaluetoaSQLstatementorastored

procedurecall.YoucanstoremultipleParameterobjectsina

CommandobjectthroughaParameterCollectionobject.



TheParameterCollectionClasses

TherearethreeParameterCollectionclasses:

SqlParameterCollection,OleDbParameterCollection,and

OdbcParameterCollection.YouuseaParameterCollection

objecttostoremultipleParameterobjectsforaCommandobject.



TheDataReaderClasses

TherearethreeDataReaderclasses:SqlDataReader,

OleDbDataReader,andOdbcDataReader.Youusea

DataReaderobjecttoreadrowsretrievedfromthedatabaseusinga

Commandobject.

DataReaderobjectscanonlybeusedtoreadrowsinaforward

direction.DataReaderobjectsactasanalternativetoaDataSet

object.YoucannotuseaDataReadertomodifyrowsinthe

database.

Tip ReadingrowsusingaDataReaderobjectistypicallyfaster

thanreadingfromaDataSet.



TheDataAdapterClasses

TherearethreeDataAdapterclasses:SqlDataAdapter,

OleDbData-Adapter,andOdbcDataAdapter.Youusea

DataAdapterobjecttomoverowsbetweenaDataSetobjectanda

database.YouuseaDataAdapterobjecttosynchronizeyourlocally

storedrowswiththedatabase.Thissynchronizationisperformed

throughaConnectionobject.Forexample,youcanreadrowsfrom



thedatabaseintoaDataSetthroughaData-Adapter,modify

thoserowsinyourDataSet,andthenpushthosechangestothe

databasethroughaConnectionobject.



TheCommandBuilderClasses

TherearethreeCommandBuilderclasses:SqlCommandBuilder,

OleDbCommandBuilder,andOdbcCommandBuilder.Youusea

CommandBuilderobjecttoautomaticallygeneratesingle-table

INSERT,UPDATE,andDELETEcommandsthatsynchronizeany

changesyoumaketoaDataSetobjectwiththedatabase.This

synchronizationisperformedthroughaDataAdapterobject.



TheTransactionClasses

TherearethreeTransactionclasses:SqlTransaction,

OleDbTransaction,andOdbcTransaction.Youusea

Transactionobjecttorepresentadatabasetransaction.A

databasetransactionisagroupofstatementsthatmodifytherowsin

thedatabase.Thesestatementsareconsideredalogicalunitofwork.

Forexample,inthecaseofabankingtransaction,youmightwantto

withdrawmoneyfromoneaccountanddeposititintoanother.You

wouldthencommitbothofthesechangesasoneunit,orifthere'sa

problem,rollbackbothchanges.



NamespacesfortheManagedProviderClasses

ThemanagedproviderclassesforSQLServer(SqlConnectionand

soon)aredeclaredintheSystem.Data.SqlClientnamespace.

TheclassesforOLEDB–compliantdatabases(SqlDbConnection

andsoon)aredeclaredintheSystem.Data.OleDbnamespace.

TheclassesforODBC-compliantdatabases(OdbcConnectionand

soon)aredeclaredintheSystem.Data.Odbcnamespace.

Inthefollowingsection,you'lllearnaboutthegenericdataclasses.



TheGenericDataClasses



Asdiscussedintheprevioussection,youcanusethemanageddata

providerobjectstoconnecttothedatabasethroughaConnection

object,issueaSQLstatementthroughaCommandobject,andread

retrievedrowsusingaDataReaderobject;however,youcanread

rowsonlyinaforward-onlydirectionandyoumustbeconnectedto

thedatabase.

Thegenericdataobjectsallowyoutostorealocalcopyofthe

informationstoredinthedatabase.Thisallowsyoutoworkthe

informationwhiledisconnectedfromthedatabase.Youcanreadthe

rowsinanyorder,andyoucansearch,sort,andfilterthoserowsina

flexiblemanner.Youcanevenmakechangestothoserowsandthen

synchronizethosechangeswiththedatabase.

Figure11.2illustratessomeofthegenericdatasetobjectsandhow

theyrelatetoeachother.Thebridgebetweenthemanagedprovider

andgenericdatasetobjectsistheDataAdapter,whichyouuseto

synchronizechangesbetweenyourDataSetandthedatabase.





Figure11.2:Someofthegenericdataset

objects



Thefollowingsectionsoutlinesomeofthegenericdataclasses.



TheDataSetClass

YouuseanobjectoftheDataSetclasstorepresentalocalcopyof

theinformationstoredinthedatabase.Youcanmakechangestothat

localcopyinyourDataSetandthenlatersynchronizethosechanges

withthedatabasethroughamanagedproviderDataAdapterobject.

ADataSetobjectcanrepresentdatabasestructuressuchastables,

rows,andcolumns.Youcanevenaddconstraintstoyourlocally

storedtablestoenforceuniqueandforeignkeyconstraints.

YoucanalsouseaDataSetobjecttorepresentXMLdata.Infact,all

informationstoredinaDataSetisrepresentedusingXML,including

informationretrievedfromthedatabase.



TheDataTableClass

YouuseanobjectoftheDataTableclasstorepresentatable.You

canstoremultipleDataTableobjectsinaDataSetthrougha

DataTableCollectionobject.ADataSetobjecthasaproperty

namedTables,whichyouusetoaccessthe

DataTableCollectioncontainingtheDataTableobjectsstored

inthatDataSet.



TheDataRowClass

YouuseanobjectoftheDataRowclasstorepresentarow.Youcan

storemultipleDataRowobjectsinaDataTablethrougha

DataRowCollectionobject.ADataTableobjecthasaproperty

namedRows,whichyouusetoaccesstheDataRowCollection

containingtheDataRowobjectsstoredinthatDataTable.



TheDataColumnClass

YouuseanobjectoftheDataColumnclasstorepresentacolumn.

YoucanstoremultipleDataColumnobjectsinaDataTablethrough



aDataColumn-Collectionobject.ADataTableobjecthasa

propertynamedColumns,whichyouusetoaccessthe

DataColumnCollectioncontainingtheDataColumnobjects

storedinthatDataTable.



TheConstraintClass

YouuseanobjectoftheConstraintclasstorepresentadatabase

constraintthatistobeenforcedononeormoreDataColumnobjects

ofaDataTable.YoucanstoremultipleConstraintobjectsina

DataTablethroughaConstraintCollectionobject.A

DataTableobjecthasapropertynamedConstraints,whichyou

usetoaccesstheConstraintCollectioncontainingthe

ConstraintobjectsstoredinthatDataTable.



TheDataViewClass

YouuseanobjectoftheDataViewclasstoviewonlyspecificrowsin

aDataTableobjectusingafilter,whichspecifiesthecriteriato

restricttherows.



TheDataRelationClass

YouuseanobjectoftheDataRelationclasstorepresenta

relationshipbetweentwoDataTableobjects.Youcanusea

DataRelationobjecttomodelparent-childrelationshipsbetween

twodatabasetables.YoucanstoremultipleDataRelationobjects

inaDataSetthroughaDataRelationCollectionobject.A

DataSetobjecthasapropertynamedRelations,whichyouuseto

accesstheDataRelationCollectioncontainingthe

DataRelationobjectsstoredinthatDataSet.



TheUniqueConstraintClass

YouuseanobjectoftheUniqueConstraintclasstorepresenta

databaseconstraintthatenforcesthatthevaluestoredina



DataColumnobjectisunique.TheUniqueConstraintclassis

derivedfromtheConstraintclass.Youcanstoremultiple

UniqueConstraintobjectsinaDataTablethrougha

ConstraintCollectionobject.



TheForeignKeyConstraintClass

YouuseanobjectoftheForeignKeyConstraintclasstospecify

theactionperformedwhenthecolumnvaluesintheparenttableare

updatedordeleted.

TheForeignKeyConstraintclassisderivedfromthe

Constraintclass.Youcaneitherhavethechildrowsdeleted

(cascadingaction),setthechildcolumnstonull,orsetthechild

columnstoadefaultvalue.Youcanstoremultiple

ForeignKeyConstraintobjectsinaDataTablethrougha

ConstraintCollectionobject.



NamespacesfortheGenericDataClasses

TheDataSet,DataTable,DataRow,DataColumn,

DataRelation,Constraint,andDataViewclassesareall

declaredintheSystem.Datanamespace.Thisnamespacecontains

otherclassesthatyoucanuseinyourprograms.Youcanviewthefull

setofclassesdeclaredintheSystem.Datanamespaceusingthe

.NETdocumentation.

Inthenextsection,you'llseeasimpleexamplethatillustrateshowto

issueaSQLSELECTstatementthatretrieverowsfromthe

Customerstable,andthenstoresthereturnedrowsinaDataSet

object.Thisprogramwillgiveyouabasicunderstandingonhowto

usesomeofthemanagedproviderandgenericdataclasses

previouslyoutlined.



PerformingaSQLSELECTStatementand

StoringtheRowsLocally

Intheexamplefeaturedinthissection,you'llseehowtoconnectto

theSQLServerNorthwinddatabaseandperformaSQLSELECT

statementtoretrievetheCustomerID,CompanyName,

ContactName,andAddresscolumnsforthefirst10rowsfromthe

Customerstable.TheserowsarestoredinaDataSetobject.

Note SinceI'llbeusingaSQLServerdatabase,I'llusetheSQL

Servermanagedproviderclassesintheexample.



OutliningtheProcedure

YoucanusethefollowingstepstoretrievetherowsintoaDataSet

object:

1. Formulateastringcontainingthedetailsofthedatabase

connection.

2. CreateaSqlConnectionobjecttoconnecttothe

database,passingtheconnectionstringtotheconstructor.

3. FormulateastringcontainingaSELECTstatementto

retrievethecolumnsfortherowsfromtheCustomerstable.

4. CreateaSqlCommandobjecttoholdtheSELECTstatement.

5. SettheCommandTextpropertyoftheSqlCommandobject

totheSELECTstring.

6. CreateaSqlDataAdapterobject.

7. SettheSelectCommandpropertyoftheSqlAdapter

objecttotheSqlCommandobject.

8. CreateaDataSetobjecttostoretheresultsoftheSELECT

statement.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 11: Overview of the ADO.NET Classes

Tải bản đầy đủ ngay(0 tr)

×