Tải bản đầy đủ - 0 (trang)
Chapter 6: Data Access Using ADO.NET

Chapter 6: Data Access Using ADO.NET

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

Lesson1:OverviewofADO.NET

Mostapplicationsrequiresomekindofdataaccess.Desktopapplicationsneedto

integratewithcentraldatabases,ExtensibleMarkupLanguage(XML)data

stores,orlocaldesktopdatabases.ADO.NETdata-accesstechnologyallows

simple,powerfuldataaccesswhilemaximizingsystemresourceusage.



Afterthislesson,youwillbeableto

DescribethemajorcomponentsofADO.NETdataaccess

Explaintheroleofeachdata-accesscomponent

DescribeingeneraltermshowADO.NETdataaccessisfacilitated



Estimatedlessontime:30minutes

Differentapplicationshavedifferentrequirementsfordataaccess.Whetheryour

applicationsimplydisplaysthecontentsofatable,orprocessesandupdatesdata

toacentralSQLserver,ADO.NETprovidesthetoolstoimplementdataaccess

easilyandefficiently.



DisconnectedDatabaseAccess

Previousdata-accesstechnologiesprovidedcontinuouslyconnecteddataaccess

bydefault.Insuchamodel,anapplicationcreatesaconnectiontoadatabaseand

keepstheconnectionopenforthelifeoftheapplication,oratleastforthe

amountoftimethatdataisrequired.However,asapplicationsbecomemore

complexanddatabasesservemoreandmoreclients,connecteddataaccessis

impracticalforavarietyofreasons,includingthefollowing:

Opendatabaseconnectionsareexpensiveintermsofsystemresources.

Themoreopenconnectionsthereare,thelessefficientsystem



performancebecomes.

Applicationswithconnecteddataaccessaredifficulttoscale.An

applicationthatcancomfortablymaintainconnectionswithtwoclients

mightdopoorlywith10andbecompletelyunusablewith100.

Opendatabaseconnectionscanquicklyconsumeallavailabledatabase

licenses,whichcanbeasignificantexpense.Inordertoworkwithina

limitedsetofclientlicenses,connectionsmustbereusedwhenever

possible.

ADO.NETaddressestheseissuesbyimplementingadisconnecteddataaccess

modelbydefault.Inthismodel,dataconnectionsareestablishedandleftopen

onlylongenoughtoperformtherequisiteaction.Forexample,ifanapplication

requestsdatafromadatabase,theconnectionopensjustlongenoughtoloadthe

dataintotheapplication,andthenitcloses.Likewise,ifadatabaseisupdated,

theconnectionopenstoexecutetheUPDATEcommand,andthenclosesagain.

Bykeepingconnectionsopenonlyfortheminimumrequiredtime,ADO.NET

conservessystemresourcesandallowsdataaccesstoscaleupwithaminimal

impactonperformance.



ADO.NETDataArchitecture

DataaccessinADO.NETreliesontwoentities:theDataSet,whichstoresdata

onthelocalmachine,andtheDataProvider,asetofcomponentsthatmediates

interactionbetweentheprogramandthedatabase.



TheDataSet

TheDataSetisadisconnected,in-memoryrepresentationofdata.Itcanbe

thoughtofasalocalcopyoftherelevantportionsofadatabase.Datacanbe

loadedintoaDataSetfromanyvaliddatasource,suchasaSQLServer

database,aMicrosoftAccessdatabase,oranXMLfile.TheDataSetpersistsin

memory,andthedatathereincanbemanipulatedandupdatedindependentofthe

database.Whenappropriate,theDataSetcanthenactasatemplateforupdating

thecentraldatabase.

TheDataSetobjectcontainsacollectionofzeroormoreDataTableobjects,each

ofwhichisanin-memoryrepresentationofasingletable.Thestructureofa



particularDataTableisdefinedbytheDataColumnscollection,which

enumeratesthecolumnsinaparticulartable,andtheConstraintcollection,

whichenumeratesanyconstraintsonthetable.Together,thesetwocollections

makeupthetableschema.ADataTablealsocontainsaDataRowscollection,

whichcontainstheactualdataintheDataSet.

TheDataSetcontainsaDataRelationscollection.ADataRelationobjectallows

youtocreateassociationsbetweenrowsinonetableandrowsinanothertable.

TheDataRelationscollectionenumeratesasetofDataRelationobjectsthat

definetherelationshipsbetweentablesintheDataSet.Forexample,considera

DataSetthatcontainstworelatedtables:anEmployeestableandaProjects

table.IntheEmployeestable,eachemployeeisrepresentedonlyonceandis

identifiedbyauniqueEmployeeIDfield.IntheProjectstable,anemployeein

chargeofaprojectisidentifiedbytheEmployeeIDfield,butcanappearmore

thanonceifthatemployeeisinchargeofmultipleprojects.Thisisanexample

ofaone-to-manyrelationship;youwoulduseaDataRelationobjecttodefine

thisrelationship.

Additionally,aDataSetcontainsanExtendedPropertiescollection,whichisused

tostorecustominformationabouttheDataSet.



TheDataProvider

Thelinktothedatabaseiscreatedandmaintainedbyadataprovider.Adata

providerisnotasinglecomponent,ratheritisasetofrelatedcomponentsthat

worktogethertoprovidedatainanefficient,performance-drivenmanner.The

firstversionoftheMicrosoft.NETFrameworkshippedwithtwodataproviders:

theSQLServer.NETDataProvider,designedspecificallytoworkwithSQL

Server7orlater,andtheOleDb.NETDataProvider,whichconnectswithother

typesofdatabases.MicrosoftVisualStudio.NET2003addedtwomoredata

providers:theODBCDataProviderandtheOracleDataProvider.Eachdata

providerconsistsofversionsofthefollowinggenericcomponentclasses:

TheConnectionobjectprovidestheconnectiontothedatabase.

TheCommandobjectexecutesacommandagainstadatasource.Itcan

executenon-querycommands,suchasINSERT,UPDATE,orDELETE,

orreturnaDataReaderwiththeresultsofaSELECTcommand.

TheDataReaderobjectprovidesaforward-only,read-only,connected



recordset.

TheDataAdapterobjectpopulatesadisconnectedDataSetorDataTable

withdataandperformsupdates.

NOTEThroughoutthischapter,wheneverinformationisapplicableto

memberclassesofanydataprovider,theclassesarereferredtobythe

genericname.Forexample,CommandcanmeanOleDbCommandor

SqlCommand.

DataaccessinADO.NETisfacilitatedasfollows:aConnectionobject

establishesaconnectionbetweentheapplicationandthedatabase.This

connectioncanbeaccesseddirectlybyaCommandobjectorbyaDataAdapter

object.TheCommandobjectprovidesdirectexecutionofacommandtothe

database.Ifthecommandreturnsmorethanasinglevalue,theCommandobject

returnsaDataReadertoprovidethedata.Thisdatacanbedirectlyprocessedby

applicationlogic.Alternatively,youcanusetheDataAdaptertofillaDataSet

object.UpdatestothedatabasecanbeachievedthroughtheCommandobjector

throughtheDataAdapter.

Thegenericclassesthatmakeupthedataprovidersaresummarizedinthe

followingsections.



TheConnectionObject

TheConnectionobjectrepresentstheactualconnectiontothedatabase.Visual

Studio.NET2003suppliestwotypesofConnectionclasses:theSqlConnection

object,whichisdesignedspecificallytoconnecttoSQLServer7orlater,and

theOleDbConnectionobject,whichcanprovideconnectionstoawiderangeof

databasetypes.VisualStudio.NET2003furtherprovidesamultipurpose

ODBCConnectionclass,aswellasanOracleConnectionclassoptimizedfor

connectingtoOracledatabases.TheConnectionobjectcontainsallofthe

informationrequiredtoopenachanneltothedatabaseintheConnectionString

property.TheConnectionobjectalsoincorporatesmethodsthatfacilitatedata

transactions.



TheCommandObject



TheCommandobjectisrepresentedbytwocorrespondingclasses,SqlCommand

andOleDbCommand.YoucanuseCommandobjectstoexecutecommandstoa

databaseacrossadataconnection.Commandobjectscanbeusedtoexecute

storedproceduresonthedatabaseandSQLcommands,orreturncomplete

tables.Commandobjectsprovidethreemethodsthatareusedtoexecute

commandsonthedatabase:

ExecuteNonQuery.

Executescommandsthatreturnnorecords,suchasINSERT,UPDATE,

orDELETE

ExecuteScalar.

Returnsasinglevaluefromadatabasequery

ExecuteReader.

ReturnsaresultsetbywayofaDataReaderobject



TheDataReaderObject

TheDataReaderobjectprovidesaforward-only,read-only,connectedstream

recordsetfromadatabase.Unlikeothercomponentsofadataprovider,

DataReaderobjectscannotbedirectlyinstantiated.Rather,theDataReaderis

returnedastheresultofaCommandobject’sExecuteReadermethod.The

SqlCommand.ExecuteReadermethodreturnsaSqlDataReaderobject,andthe

OleDbCommand.ExecuteReadermethodreturnsanOleDbDataReaderobject.

Likewise,theODBCandOracleCommand.ExecuteReadermethodsreturna

DataReaderspecifictotheODBCandOracleDataProvidersrespectively.The

DataReadercansupplyrowsofdatadirectlytoapplicationlogicwhenyoudo

notneedtokeepthedatacachedinmemory.Becauseonlyonerowisinmemory

atatime,theDataReaderprovidesthelowestoverheadintermsofsystem

performance,butitrequiresexclusiveuseofanopenConnectionobjectforthe

lifetimeoftheDataReader.



TheDataAdapterObject

TheDataAdapteristheclassatthecoreofADO.NETdisconnecteddataaccess.

Itisessentiallythemiddleman,facilitatingallcommunicationbetweenthe



databaseandaDataSet.TheDataAdapterfillsaDataTableorDataSetwithdata

fromthedatabasewhenevertheFillmethodiscalled.Afterthememory-resident

datahasbeenmanipulated,theDataAdaptercantransmitchangestothe

databasebycallingtheUpdatemethod.TheDataAdapterprovidesfour

propertiesthatrepresentdatabasecommands.Thefourpropertiesare:

SelectCommand.

Containsthecommandtextorobjectthatselectsthedatafromthe

database.ThiscommandisexecutedwhentheFillmethodiscalledand

fillsaDataTableoraDataSet.

InsertCommand.

Containsthecommandtextorobjectthatinsertsarowintoatable.

DeleteCommand.

Containsthecommandtextorobjectthatdeletesarowfromatable.

UpdateCommand.

Containsthecommandtextorobjectthatupdatesthevaluesofa

database.

WhentheUpdatemethodiscalled,changesintheDataSetarecopiedbackto

thedatabase,andtheappropriateInsertCommand,DeleteCommand,or

UpdateCommandisexecuted.



LessonSummary

ADO.NETisadata-accesstechnologythatisprimarilydisconnected

anddesignedtoprovideefficient,scalabledataaccess.

DataisrepresentedwithinaDataSetobject,whichisadisconnected,inmemorycopyofpartorallofadatabase.

Adataproviderisasetofclassesthatprovideaccesstodatabases.The

maincomponentsofdataprovidersare:

Connection

Command



DataReader

DataAdapter

VisualStudio.NETincludestwodataproviders:

TheSQLDataProvider,whichcontainsclassesoptimizedfor

accessingSQLServer7orlater

TheOleDbDataProvider,whichcontainsclassesthatprovide

accesstoabroadrangeofdatabaseformats

TwoadditionaldataprovidersareincludedinVisualStudio.NET2003:

TheODBCDataProvider,whichfacilitatesaccesstomany

differentdatabaseformats

TheOracleDataProvider,whichcontainsclassesoptimizedfor

accessingOracledatabases



Lesson2:OverviewofStructuredQueryLanguage

StructuredQueryLanguage(SQL)istheuniversallanguageofrelational

databases.SQLcanbeusedtoretrieveandfilterrecordsfromdatabases,toadd

recordstodatabases,todeleterecordsfromadatabase,andtochangethevalues

ofanexistingrecord.

UsingSQLstatementsbehindthescenes,ADO.NEThandlesmostoftheactual

databaseinteractionforyouthroughtheclassescontainedinadataprovider.In

somecases,though,itisimportanttobeabletogenerateSQLstatementsto

interactdirectlywithadatabase.Forexample,youmightwanttodynamically

buildSQLstatementsinresponsetouserinputtoretrieveacustomsetofrows.

Inthislesson,youwilllearnthebasicsofSQLsyntax.



Afterthislesson,youwillbeableto

DescribebasicSQLsyntax

ConstructsimpleSELECT,UPDATE,INSERT,andDELETE

commands

UsetheWHEREclausetofiltertheresultsreturnedbyaSQLqueryand

usetheORDERBYclausetospecifyasortorder



Estimatedlessontime:30minutes

StructuredQueryLanguageusesfourbasicstatementstointeractwitha

database.TheSELECTstatementisusedtoretrieverecordsfromadatabase;the

UPDATEstatementisusedtoupdatedatainadatabase;theINSERTstatement

isusedtoinsertanewrowintoatable;andtheDELETEstatementisusedto

deletearecord.

NOTETheinformationprovidedinthissectioncoversonlythebasics



ofStructuredQueryLanguage—itshouldnotbeconsidered

comprehensive.Youareencouragedtosupplementyourreadingwith

additionaltextsifyoufindthesubjectinteresting.



TheSELECTStatement

TheSELECTstatementisthecommandusedtoretrieverecordsfroma

database.ASELECTstatementcanbedividedintofoursegments:

SELECT.

Thissegmentallowsyoutospecifywhichfieldswillberetrieved.

FROM.

Thissegmentallowsyoutospecifywhichtableortableswillbeusedto

getthefieldsspecifiedintheSELECTsegment.

WHERE.

(Optional)Thissegmentallowsyoutoapplyfilterconditionstothe

rowsretrieved.

ORDERBY.

(Optional)Thissegmentallowsyoutospecifyafieldbywhichtoorder

thereturnedrecords.

TheminimumsyntaxforanSQLSELECTstatementisasfollows:



SELECTfieldsFROMtables;

fieldsrepresentsthefieldorfieldstoberetrieved,andtablesrepresentsthetable

ortableswherethosefieldswillbefound.Forexample,toretrievethe

EmployeeIDandStartDatefieldsfromtheEmployeestable,youusethe

followingstatement:



SELECTEmployeeID,StartDateFROMEmployees;



NOTE

InSQLServer,SQLstatementsareterminatedwithasemicolon(;).

Youcanusethe*charactertorepresentallfieldsinatableortables.Thus,if

youwantedtoretrieveallfieldsfromtheEmployeestable,yourquerywould

looklikethis:



SELECT*FROMEmployees;

NOTE

Ifspecificfieldsarerequiredforaquery,youshouldselectthespecific

fieldsinsteadofusingthe*character.Thisensuresthatthecorrect

fieldsarealwaysreturnedinthesameorderregardlessofanydata-table

changesthatmighthaveoccurred.



TheWHEREclause

Youmightwanttolimitorfiltertherecordsthatyouretrievefromthedatabase,

suchasonlytherecordswithaparticularvalueinonefield—theoptional

WHEREclausegivesyouthischoice.Toillustrate,thefollowingstatement

selectsallrecordsfromtheEmployeestableifthevalueoftheFirstNamefieldis

‘Bob’:



SELECT*

FROMEmployees

WHEREFirstName='Bob';

NOTE

TospecifyastringliteralinanSQLstatement,youmustenclosethe

literalinsinglequotes('').

YoucanuselogicaloperatorssuchasANDorORtospecifymultipleconditions.

ThefollowingcodeexampleretrievesallrecordsfromtheEmployeestable

wheretheLastNamefieldis‘Jones’andtheFirstNamefieldis‘Joe’:



SELECT*

FROMEmployees

WHEREFirstName='Joe'ANDLastName='Jones';

YoucanusetheINoperatortoretrieverecordsbymatchingthevalueofafield

tovaluesspecifiedinalist.ThefollowingSQLstatementshowsanexampleof

WHERE…IN.ThisstatementwillretrievetheFirstNameandLastNamefields

fromtheEmployeestableiftheCountryfieldis‘US’or‘UK’:



SELECTFirstName,LastName

FROMEmployees

WHERECountryIN('UK','US');

YoualsocanusetheBETWEENoperatortospecifythatavaluelieswithina

specifiedrange.ThisexampleretrievesallrecordsfromtheSalestableifthe

FinalPricefieldisbetween100and200:



SELECT*

FROMSales

WHEREFinalPriceBETWEEN100AND200;

TheWHEREclausealsoallowsyoutosearchstringfieldsforsimilar,butnot

exact,matchesusingtheLIKEoperator.TheLIKEoperatorallowsyoutouse

wildcardcharacterstospecifyapatterntomatch.InanSQLquery,the

underscore(_)characterrepresentsanysinglecharacter,andthepercent(%)

characterrepresentsanynumberofcharacters.ThefollowingSQLstatementis

anexample:



SELECT*

FROMEmployees

WHEREFirstNameLIKE'Wil_';

Thisstatementmatches‘Will’butnot‘Willy’or‘William’.Thescenariochanges

inthefollowingcodeexample:



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

Chapter 6: Data Access Using ADO.NET

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

×
x