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

Chapter 5: Overview of the ADO.NET Classes

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

Overview

ADO.NETallowsyoutointeractwithadatabasedirectlyusingobjectsof

themanagedproviderclasses.Theseobjectsallowyoutoconnecttothe

databaseandexecuteSQLstatementswhiledirectlyconnectedtothe

database.TheexampleprogramyousawinChapter1showedhowto

connecttoadatabasedirectlyandreadtherowsfromatableina

forward-onlydirection.

ADO.NETalsoallowsyoutoworkinadisconnectedmanner.When

doingthis,youstoreinformationfromadatabaselocallyinthememoryof

thecomputeronwhichyourprogramisrunning.Youstorethat

informationusingobjectsofthedatasetclasses.Onceyouhavethat

informationinthememory,youcanthenreadandmanipulatethat

information.Forexample,youcandisplaythecolumnsfortherows,add

newrows,modifyrows,anddeleterows.Periodically,you'llreconnectto

thedatabasetosynchronizeyourchangesyou'vemadelocallywiththe

database.Thisdisconnectedmodelallowsyoutowriteapplicationsthat

runontheInternet,aswellasfordevicesthataren'talwaysconnectedto

thedatabase-PDAssuchasthePalmandthePocketPC,forexample.

ThischapterprovidesdescriptionsoftheADO.NETclasses,aswellasa

completeC#programthatconnectstoadatabase,storestherows

locally,disconnectsfromthedatabase,andthenreadsthecontentsof

thoselocalrowswhiledisconnectedfromthedatabase.Thiscapabilityto

storealocalcopyofrowsretrievedfromthedatabaseisoneofthemain

strengthsofADO.NET.Theexampleprogramillustratesthebasicideas

ofusingtheADO.NETdisconnectedmodeltoreadrowsfromthe

databaseandstorethemlocallyinmemory.Inlaterchapters,you'llsee

howtomodifydatalocallyandthensynchronizethosechangeswiththe

database.

ThischapterlaysthefoundationforPartII,"FundamentalDatabase

ProgrammingwithADO.NET,"whereyou'llseethedetailsofthevarious

ADO.NETclasses.



Featuredinthischapter:

TheManagedProviderandGenericDataSetClasses

PerformingaSQLSELECTStatementandStoringtheRows

Locally



TheManagedProviderandGenericDataSet

Classes

Toprovidebothconnectedanddisconnecteddatabaseaccess,

ADO.NETdefinestwosetsofclasses:managedproviderandgeneric

data.

Youuseobjectsofthemanagedproviderclassestodirectlyconnecttoa

databaseandtosynchronizeyourlocallystoreddatawiththedatabase.

Youcanusethemanagedproviderclassestoreadrowsfromthe

databaseinaforward-onlydirection.Youuseadifferentsetofmanaged

providerclassesdependingonthedatabaseyouuse.

Youuseobjectsofthegenericdataclassestostorealocalcopyofthe

informationretrievedfromthedatabase.Thiscopyisstoredinthe

memoryofthecomputerwheretheC#programisrunning.Themain

genericdataclassistheSystem.Data.DataSetclass.Thegeneric

dataclasses,astheirnamesuggests,arenotspecifictoanydatabase,

andyoualwaysusethesameclassesregardlessofthedatabaseyou

use.Thegenericdataclassesrepresentinformationretrievedfromthe

databaseasXML.



TheManagedProviderClasses

Themanagedproviderobjectsallowyoutodirectlyaccessadatabase,

andyou'llbeintroducedtotheclassesthatallowyoutocreatethese

objectsinthissection.Youusethemanagedproviderobjectstoconnect

tothedatabaseandreadandwriteinformationtoandfromthedatabase.

Figure5.1illustratessomeofthemanagedproviderobjectsandhowthey

relatetoeachother.



Figure5.1:Someofthe

managedproviderobjects

Therearecurrentlythreesetsofmanagedproviderclasses,andeachset

isdesignedtoworkwithdifferentdatabasestandards:

SQLServerManagedProviderClassesYouusetheSQL

ServermanagedproviderclassestoconnecttoaSQLServer

database.

OLEDBManagedProviderClassesYouusetheOLEDB

(ObjectLinkingandEmbeddingforDatabases)managed

providerclassestoconnecttoanydatabasethatsupportsOLE

DB,suchasAccessorOracle.

ODBCManagedProviderClassesYouusetheODBC(Open

DatabaseConnectivity)managedproviderclassestoconnectto

anydatabasethatsupportsODBC.Allthemajordatabases

supportODBC,butODBCistypicallyslowerthantheprevious

twosetsofclasseswhenworkingwith.NET.Youshouldusethe

ODBCmanagedproviderclassesonlywhentherearen'tany

alternativeOLEDBmanagedproviderclasses.



Thesethreesetsofclassesallimplementthesamebasic

functionality.

Note WheneveryouseeSqlatthestartofamanagedprovider

classname,youknowthatclassisusedwithaSQLServer

database.Forexample,SqlConnectionallowsyouto

connecttoaSQLServerdatabase.Similarly,OleDbisfor

databasesthatsupportOLEDB.Forexample,

OleDbConnectionallowsyoutoconnecttoadatabaseusing

OLEDB.Finally,OdbcisfordatabasesthatsupportODBC.For

example,OdbcConnectionallowsyoutoconnecttoa

databaseusingODBC.Irefertoalloftheseclassesasthe

Connectionclasses.

You'llseesomeofthevariousmanagedproviderclassesinthefollowing

sections.



TheConnectionClasses

TherearethreeConnectionclasses:SqlConnection,

OleDbConnection,andOdbcConnection.Youuseanobjectofthe

SqlConnectionclasstoconnecttoaSQLServerdatabase.Youuse

anobjectoftheOleDbConnectionclasstoconnecttoanydatabase

thatsupportsOLEDB,suchasAccessorOracle.Youuseanobjectof

theOdbcConnectionclasstoconnecttoanydatabasethatsupports

ODBC.Ultimately,allcommunicationwithadatabaseisdonethrougha

Connectionobject.



TheCommandClasses

TherearethreeCommandclasses:SqlCommand,OleDbCommand,and

OdbcCommand.YouuseaCommandobjecttorunaSQLstatement,such

asaSELECT,INSERT,UPDATE,orDELETEstatement.Youcanalsouse

aCommandobjecttocallastoredprocedureorretrieverowsfroma

specifictable.YourunthecommandstoredinaCommandobjectusinga

Connectionobject.



TheParameterClasses

TherearethreeParameterclasses:SqlParameter,

OleDbParameter,andOdbcParameter.YouuseaParameterobject

topassaparametertoaCommandobject.YoucanuseaParameterto

passavaluetoaSQLstatementorastoredprocedurecall.Youcan

storemultipleParameterobjectsinaCommandobjectthrougha

ParameterCollectionobject.



TheParameterCollectionClasses

TherearethreeParameterCollectionclasses:

SqlParameterCollection,OleDbParameterCollection,and

OdbcParameterCollection.YouuseaParameterCollection

objecttostoremultipleParameterobjectsforaCommandobject.



TheDataReaderClasses

TherearethreeDataReaderclasses:SqlDataReader,

OleDbDataReader,andOdbcDataReader.YouuseaDataReader

objecttoreadrowsretrievedfromthedatabaseusingaCommandobject.

DataReaderobjectscanonlybeusedtoreadrowsinaforward

direction.DataReaderobjectsactasanalternativetoaDataSet

object.YoucannotuseaDataReadertomodifyrowsinthedatabase.

Tip ReadingrowsusingaDataReaderobjectistypicallyfasterthan

readingfromaDataSet.



TheDataAdapterClasses

TherearethreeDataAdapterclasses:SqlDataAdapter,

OleDbDataAdapter,andOdbcDataAdapter.Youusea

DataAdapterobjecttomoverowsbetweenaDataSetobjectanda

database.YouuseaDataAdapterobjecttosynchronizeyourlocally

storedrowswiththedatabase.Thissynchronizationisperformedthrough

aConnectionobject.Forexample,youcanreadrowsfromthe



databaseintoaDataSetthroughaDataAdapter,modifythoserowsin

yourDataSet,andthenpushthosechangestothedatabasethrougha

Connectionobject.



TheCommandBuilderClasses

TherearethreeCommandBuilderclasses:SqlCommandBuilder,

OleDbCommandBuilder,andOdbcCommandBuilder.Youusea

CommandBuilderobjecttoautomaticallygeneratesingle-tableINSERT,

UPDATE,andDELETEcommandsthatsynchronizeanychangesyou

maketoaDataSetobjectwiththedatabase.Thissynchronizationis

performedthroughaDataAdapterobject.



TheTransactionClasses

TherearethreeTransactionclasses:SqlTransaction,

OleDbTransaction,andOdbcTransaction.Youusea

Transactionobjecttorepresentadatabasetransaction.Adatabase

transactionisagroupofstatementsthatmodifytherowsinthedatabase.

Thesestatementsareconsideredalogicalunitofwork.Forexample,in

thecaseofabankingtransaction,youmightwanttowithdrawmoney

fromoneaccountanddeposititintoanother.Youwouldthencommit

bothofthesechangesasoneunit,orifthere'saproblem,rollbackboth

changes.



NamespacesfortheManagedProviderClasses

ThemanagedproviderclassesforSQLServer(SqlConnectionandso

on)aredeclaredintheSystem.Data.SqlClientnamespace.The

classesforOLEDB-compliantdatabases(SqlDbConnectionandso

on)aredeclaredintheSystem.Data.OleDbnamespace.Theclasses

forODBC-compliantdatabases(OdbcConnectionandsoon)are

declaredintheSystem.Data.Odbcnamespace.

Note Attimeofwriting,youhavetodownloadtheODBCmanaged

providerclassesfromMicrosoft'sWebsiteat

http://msdn.microsoft.com/downloads.Thisdownloadis



separatefromthe.NETSDK.Lookfor"ODBC.NETData

Provider"intheMSDNtableofcontents.

Inthefollowingsection,you'lllearnaboutthegenericdataclasses.



TheGenericDataClasses

Asyoulearnedintheprevioussection,youcanusethemanageddata

providerobjectstoconnecttothedatabasethroughaConnection

object,issueaSQLstatementthroughaCommandobject,andread

retrievedrowsusingaDataReaderobject;however,youcanreadrows

onlyinaforwardonlydirectionandyoumustbeconnectedtothe

database.

Thegenericdataobjectsallowyoutostorealocalcopyofthe

informationstoredinthedatabase.Thisallowsyoutoworkthe

informationwhiledisconnectedfromthedatabase.Youcanreadtherows

inanyorder,andyoucansearch,sort,andfilterthoserowsinaflexible

manner.Youcanevenmakechangestothoserowsandthen

synchronizethosechangeswiththedatabase

Figure5.2illustratessomeofthegenericdatasetobjectsandhowthey

relatetoeachother.Thebridgebetweenthemanagedproviderand

genericdatasetobjectsistheDataAdapter,whichyouuseto

synchronizechangesbetweenyourDataSetandthedatabase.





Figure5.2:Someofthegenericdatasetobjects

Thefollowingsectionsoutlinesomeofthegenericdataclasses.



TheDataSetClass

YouuseanobjectoftheDataSetclasstorepresentalocalcopyofthe

informationstoredinthedatabase.Youcanmakechangestothatlocal

copyinyourDataSetandthenlatersynchronizethosechangeswiththe

databasethroughamanagedproviderDataAdapterobject.ADataSet

objectcanrepresentdatabasestructuressuchastables,rows,and

columns.Youcanevenaddconstraintstoyourlocallystoredtablesto

enforceuniqueandforeignkeyconstraints.

YoucanalsouseaDataSetobjecttorepresentXMLdata.Infact,all

informationstoredinaDataSetisrepresentedusingXML,including

informationretrievedfromthedatabase.



TheDataTableClass

YouuseanobjectoftheDataTableclasstorepresentatable.Youcan



storemultipleDataTableobjectsinaDataSetthrougha

DataTableCollectionobject.ADataSetobjecthasaproperty

namedTables,whichyouusetoaccesstheDataTableCollection

containingtheDataTableobjectsstoredinthatDataSet.



TheDataRowClass

YouuseanobjectoftheDataRowclasstorepresentarow.Youcan

storemultipleDataRowobjectsinaDataTablethrougha

DataRowCollectionobject.ADataTableobjecthasaproperty

namedRows,whichyouusetoaccesstheDataRowCollection

containingtheDataRowobjectsstoredinthatDataTable.



TheDataColumnClass

YouuseanobjectoftheDataColumnclasstorepresentacolumn.You

canstoremultipleDataColumnobjectsinaDataTablethrougha

DataColumnCollectionobject.ADataTableobjecthasaproperty

namedColumns,whichyouusetoaccessthe

DataColumnCollectioncontainingtheDataColumnobjectsstoredin

thatDataTable.



TheConstraintClass

YouuseanobjectoftheConstraintclasstorepresentadatabase

constraintthatistobeenforcedononeormoreDataColumnobjectsof

aDataTable.YoucanstoremultipleConstraintobjectsina

DataTablethroughaConstraintCollectionobject.ADataTable

objecthasapropertynamedConstraints,whichyouusetoaccess

theConstraintCollectioncontainingtheConstraintobjects

storedinthatDataTable.



TheDataViewClass

YouuseanobjectoftheDataViewclasstoviewonlyspecificrowsina

DataTableobjectusingafilter,whichspecifiesthecriteriatorestrictthe



rows.



TheDataRelationClass

YouuseanobjectoftheDataRelationclasstorepresenta

relationshipbetweentwoDataTableobjects.Youcanusea

DataRelationobjecttomodelparent-childrelationshipsbetweentwo

databasetables.YoucanstoremultipleDataRelationobjectsina

DataSetthroughaDataRelationCollectionobject.ADataSet

objecthasapropertynamedRelations,whichyouusetoaccessthe

DataRelationCollectioncontainingtheDataRelationobjects

storedinthatDataSet.



TheUniqueConstraintClass

YouuseanobjectoftheUniqueConstraintclasstorepresenta

databaseconstraintthatenforcesthatthevaluestoredinaDataColumn

objectisunique.TheUniqueConstraintclassisderivedfromthe

Constraintclass.YoucanstoremultipleUniqueConstraintobjects

inaDataTablethroughaConstraintCollectionobject.



TheForeignKeyConstraintClass

YouuseanobjectoftheForeignKeyConstraintclasstospecifythe

actionperformedwhenthecolumnvaluesintheparenttableareupdated

ordeleted.

TheForeignKeyConstraintclassisderivedfromtheConstraint

class.Youcaneitherhavethechildrowsdeleted(cascadingaction),set

thechildcolumnstonull,orsetthechildcolumnstoadefaultvalue.You

canstoremultipleForeignKeyConstraintobjectsinaDataTable

throughaConstraintCollectionobject.



NamespacesfortheGenericDataClasses

TheDataSet,DataTable,DataRow,DataColumn,DataRelation,

Constraint,andDataViewclassesarealldeclaredinthe



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

Chapter 5: Overview of the ADO.NET Classes

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

×