Tải bản đầy đủ - 0 (trang)
Appendix A: Data Access with ADO.NET

Appendix A: Data Access with ADO.NET

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

Overview

byAndrewTroelsen

ThisisChapter13ofC#andthe.NETPlatform(Apress,2001).

Fromthispointon,allreferencestootherchaptersandappendixes

aretothosefromTroelsenandnottochaptersandappendixes

withinDistributed.NETProgramminginC#.

Unlessyouareavideogamedeveloperbytrade,youareprobably

interestedindatabasemanipulation.Asyouwouldexpect,the.NET

platformdefinesanumberoftypes(inahandfulofrelatednamespaces)

thatallowyoutointeractwithlocalandremotedatastores.Collectively

speaking,thesenamespacesareknownasADO.NET,whichasyouwill

seeisamajoroverhauloftheclassicADOobjectmodel.

Thischapterbeginsbyexaminingsomecoretypesdefinedinthe

System.Datanamespace—specificallyDataColumn,DataRow,and

DataTable.Theseclassesallowyoutodefineandmanipulatealocalinmemorytableofdata.Next,youspendagooddealoftimelearning

aboutthecenterpieceofADO.NET,theDataSet.Asyouwillsee,the

DataSetisanin-memoryrepresentationofacollectionofinterrelated

tables.Duringthisdiscussion,youwilllearnhowtoprogrammatically

modeltablerelationships,createcustomviewsfromagiventable,and

submitqueriesagainstyourin-memoryDataSet.

AfterdiscussinghowtomanipulateaDataSetinmemory,theremainder

ofthischapterillustrateshowtoobtainapopulatedDataSetfroma

DatabaseManagementSystem(DBMS)suchasMSSQLServer,

Oracle,orMSAccess.Thisentailsanexaminationof.NET"managed

providers"andtheOleDbDataAdapterandSqlDataAdaptertypes.



TheNeedforADO.NET

TheveryfirstthingyoumustunderstandwhenlearningADO.NETisthat

itisnotsimplythelatestandgreatestversionofclassicADO.Whileitis

truethatthereissomesymmetrybetweenthetwosystems(e.g.,each

hastheconceptof"connection"and"command"objects),somefamiliar

types(e.g.,theRecordset)nolongerexist.Furthermore,therearea

numberofnewADO.NETtypesthathavenodirectequivalentunder

classicADO(e.g.,theDataSet).

Inanutshell,ADO.NETisanewdatabaseaccesstechnologyspecifically

gearedatfacilitatingthedevelopmentofdisconnectedsystemsusingthe

.NETplatform.N-tierapplications(especiallyWeb-basedapplications)

arefastbecomingthenorm,ratherthantheexception,formostnew

developmentefforts.

UnlikeclassicADO,whichwasprimarilydesignedfortightlycoupled

client/serversystems,ADO.NETgreatlyextendsthenotionofthe

primitiveADOdisconnectedrecordsetwithanewcreaturenamedthe

DataSet.Thistyperepresentsalocalcopyofanynumberofrelated

tables.UsingtheDataSet,theclientisabletomanipulateandupdateits

contentswhiledisconnectedfromthedatasourceandsubmitthe

modifieddatabackforprocessingusingarelated"dataadapter."

AnothermajordifferencebetweenclassicADOandADO.NETisthat

ADO.NEThasfullsupportforXMLdatarepresentation.Infact,thedata

obtainedfromadatastoreisinternallyrepresented,andtransmitted,as

XML.GiventhatXMListransportedbetweenlayersusingstandard

HTTP,ADO.NETisnotlimitedbyfirewallconstraints.

Asyoumightbeaware,classicADOmakesuseoftheCOMmarshaling

protocoltomovedatabetweentiers.Whilethiswasappropriateinsome

situations,COMmarshalingposesanumberoflimitations.Specifically,

mostfirewallsareconfiguredtorejectCOMRPCpackets,whichmakes

movingdatabetweenmachinestricky.

PerhapsthemostfundamentaldifferencebetweenclassicADOand

ADO.NETisthatADO.NETisamanagedlibraryofcodeandtherefore



playsbyallthesamerulesasanymanagedlibrary.Thetypesthat

compriseADO.NETusetheCLRmemorymanagementprotocol,adhere

tothesameprogrammingmodel,andworkwithmanylanguages.

Therefore,thetypes(andtheirmembers)areaccessedinthesame

exactmanner,regardlessofwhich.NET-awarelanguageyouuse.



ADO.NET:TheBigPicture

ThetypesthatcomposeADO.NETworktogetherforacommongoal:

populateaDataSet,disconnectfromthedatastore,andreturnthe

DataSettothecaller.ADataSetisaveryinterestingdatatype,giventhat

itrepresentsalocalcollectionoftables(aswellastherelationships

betweenthesetables)usedbytheclientapplication.Insomerespects,

thismayremindyouoftheclassicADOdisconnectedrecordset.Thekey

differenceisthatadisconnectedrecordsetrepresentsasingletableof

data,whereasADO.NETDataSetscanmodelacollectionofrelated

tables.Infact,itiscompletelypossibletohaveaclient-sideDataSetthat

representstheentireremotedatabase.

OnceyouhaveobtainedaDataSet,youcanperformqueriesagainstthe

localtablestoobtainspecificsubsetsofinformationaswellasnavigate

betweenrelatedtablesprogrammatically.Asyouwouldexpect,youcan

addnewrowstoagiventableintheDataSetaswellasremove,filter,or

updateexistingrecords.Oncethemodificationshavebeenmade,the

clientthensubmitsthemodifiedDataSetbacktothedatastorefor

processing.

Anobviousquestionatthispointis"HowdoIgettheDataSet?"Under

theADO.NETmodel,DataSetsarepopulatedthroughtheuseofa

managedprovider,whichisacollectionofclassesthatimplementasetof

coreinterfacesdefinedintheSystem.Datanamespace;specifically

IDbCommand,IDbDataAdapter,IDbConnection,andIDataReader(see

Figure13-1).



Figure13-1:Clients

interactingwithmanagedproviders

ADO.NETshipswithtwomanagedprovidersoutofthebox.Firstisthe

SQLprovider,whichprovideshighlyoptimizedinteractionswithdata

storedinMSSQLServer(7.0orhigher).Ifthedatayoudesireisnotin

anSQLServerdatafile,youcanusetheOleDbprovider,whichallows

accesstoanydatastorethatsupportstheOLEDBprotocol.Beaware,

however,thattheOleDbproviderusesnativeOLEDB(andtherefore

requiresCOMInterop)toenabledataaccess.

Asyoumightsuspect,thisisalwaysaslowerprocessthantalkingtoa

datastoreinitsnativetongue.Othervendorswillsoonbeginshipping

custom-managedprovidersfortheirproprietarydatastores.Untilthen,

theOleDbproviderdoesthetrick.



UnderstandingADO.NETNamespaces

Likeotheraspectsofthe.NETuniverse,ADO.NETisdefinedinahandful

ofrelatednamespaces.Table13-1givesaquickrundownofeach.

Table13-1:ADO.NETNamespaces

ADO.NET

NAMESPACE



MEANINGINLIFE



System.Data



Thisisthecorenamespaceof

ADO.NET.Itdefinestypesthat

representtables,rows,columns,

constraints,andDataSets.This

namespacedoesnotdefinetypesto

connecttoadatasource.Rather,it

definesthetypesthatrepresentthe

dataitself.



System.Data.Common



Thisnamespacecontainsthetypes

sharedbetweenmanagedproviders.

Manyofthesetypesfunctionasbase

classestotheconcretetypesdefinedby

theOleDbandSqlClientmanaged

providers.



System.Data.OleDb



Thisnamespacedefinesthetypesthat

allowyoutoconnecttoanOLEDB–

compliantdatasource,submitSQL

queries,andfillDataSets.Thetypesin

thisnamespacehavealookandfeel

similar(butnotidentical)tothatof

classicADO.



System.Data.SqlClient



Thisnamespacedefinesthetypesthat

constitutetheSQL-managedprovider.

Usingthesetypes,youcantalkdirectly

toMicrosoftSQLServerandavoidthe

levelofindirectionassociatedwiththe



OleDbequivalents.



System.Data.SqlTypes



Thesetypesrepresentnativedatatypes

usedinMicrosoftSQLServer.Although

youarealwaysfreetousethe

correspondingCLRdatatypes,the

SqlTypesareoptimizedtoworkwith

SQLServer.



AlloftheseADO.NETnamespacesareinasingleassemblynamed

System.Data.dll(Figure13-2).Thus,likeinanyprojectreferencing

externalassemblies,youmustbesuretosetareferencetothis.NET

binary.



Figure13-2:The

System.Data.dllassembly

OfalltheADO.NETnamespaces,System.Dataisthelowestcommon

denominator.YousimplycannotbuildADO.NETapplicationswithout

specifyingthisnamespaceinyourdataaccessapplications.Inaddition,

toestablishaconnectionwithadatastore,youalsoneedtospecifya

usingdirectivefortheSystem.Data.OleDborSystem.Data.SqlClient

namespaces.Theexactreasonsforthisarediscussedsoon.Fornow,

gettoknowsomeofthecoretypesdefinedinSystem.Data.



TheTypesofSystem.Data

Asmentioned,thisnamespacecontainstypesthatrepresentthedata

youobtainfromadatastore,butnotthetypesthatmaketheliteral

connection.Inadditiontoanumberofdatabase-centricexceptions

(NoNullAllowedException,RowNotInTableException,

MissingPrimaryKeyException,andthelike),thesetypesarelittlemore

thanOOrepresentationsofcommondatabaseprimitives(tables,rows,

columns,constraints,andsoon).Table13-2listssomeofthecoretypes,

groupedbyrelatedfunctionality.

Table13-2:TypesoftheSystem.DataNamespace

SYSTEM.DATATYPE



DataColumnCollection

DataColumn



ConstraintCollection

Constraint



DataRowCollection

DataRow



DataRowView

DataView



MEANINGINLIFE

DataColumnCollectionisusedto

representallofthecolumnsusedbya

givenDataTable.DataColumn

representsaspecificcolumnina

DataTable.

ConstraintCollectionrepresentsall

constraints(foreignkeyconstraints,

uniqueconstraints)assignedtoagiven

DataTable.Constraintrepresentsan

OOwrapperaroundasingleconstraint

assignedtooneormoreDataColumns.

Thesetypesrepresentacollectionof

rowsforaDataTable

(DataRowCollection)andaspecificrow

ofdatainaDataTable(DataRow).

DataRowViewallowsyoutocarveouta

predefinedviewfromanexistingrow.

DataViewrepresentsacustomizedview

ofaDataTablethatcanbeusedfor

sorting,filtering,searching,editing,and

navigating.



DataSet



ForeignKeyConstraint

UniqueConstraint



DataRelationCollection

DataRelation

DataTableCollection

DataTable



Representsanin-memorycacheof

data,whichmayconsistofmultiple

relatedDataTables.

ForeignKeyConstraintrepresentsan

actionrestrictionenforcedonasetof

columnsinaprimarykey/foreignkey

relationship.TheUniqueConstrainttype

representsarestrictiononasetof

columnsinwhichallvaluesmustbe

unique.

Thiscollectionrepresentsall

relationships(i.e.,DataRelationtypes)

betweenthetablesinaDataSet.

DataTableCollectionrepresentsallthe

tables(i.e.,DataTabletypes)fora

particularDataSet.



Togettheballrolling,thefirsthalfofthischapterdiscusseshowto

manipulatetheseitemsinadisconnectedmodebyhand.Onceyou

understandhowtobuildaDataSetintheraw,youshouldhaveno

problemmanipulatingaDataSetpopulatedbyamanagedprovider.



ExaminingtheDataColumnType

TheDataColumntyperepresentsasinglecolumnmaintainedbya

DataTable.Collectivelyspeaking,thesetofallDataColumntypesbound

toagivenDataTablerepresentsthetable'sschema.Forexample,

assumeyouhaveatablenamedEmployeeswiththreecolumns(EmpID,

FirstName,andLastName).Programmatically,youwouldusethree

ADO.NETDataColumnobjectstorepresenttheminmemory.Asyouwill

seeinjustamoment,theDataTabletypemaintainsaninternalcollection

(whichisaccessedusingtheColumnsproperty)tomaintainits

DataColumntypes.

Ifyouhaveabackgroundinrelationaldatabasetheory,youknowthata

givencolumninadatatablecanbeassignedasetofconstraints(e.g.,

configuredasaprimarykey,assignedadefaultvalue,configuredto

containread-onlyinformation,andsoon).Also,everycolumninatable

mustmaptoanunderlyingdatatype(int,varchar,andsoforth).For

example,theEmployeestable'sschemamaydemandthattheEmpID

columnmapstoaninteger,whileFirstNameandLastNamemaptoan

arrayofcharacters.TheDataColumnclasshasnumerouspropertiesthat

allowyoutoconfiguretheseverythings.Table13-3providesarundown

ofsomecoreproperties.

Table13-3:PropertiesoftheDataColumn

DATACOLUMN

PROPERTY



MEANINGINLIFE



AllowDBNull



Usedtoindicateifarowcanspecifynull

valuesinthiscolumn.Thedefaultvalueis

true.



AutoIncrement

AutoIncrementSeed

AutoIncrementStep



Thesepropertiesareusedtoconfigurethe

autoincrementbehaviorforagiven

column.Thiscanbehelpfulwhenyouwish

toensureuniquevaluesinagiven

DataColumn(suchasaprimarykey).By

default,aDataColumndoesnotsupport



autoincrementation.

Caption



Getsorsetsthecaptiontobedisplayedfor

thiscolumn(forexample,whattheend

userseesinaDataGrid).



ColumnMapping



Thispropertydetermineshowa

DataColumnisrepresentedwhena

DataSetissavedasanXMLdocument

usingtheDataSet.WriteXml()method.



ColumnName



Getsorsetsthenameofthecolumninthe

Columnscollection(meaninghowitis

representedinternallybytheDataTable).If

youdonotsettheColumnNameexplicitly,

thedefaultvaluesareColumnwith(n+1)

numericalsuffixes(i.e.,Column1,

Column2,Column3,andsoforth).



DataType



Definesthedatatype(boolean,string,

float,andsoon)storedinthecolumn.



DefaultValue



Getsorsetsthedefaultvalueassignedto

thiscolumnwheninsertingnewrows.This

isusedifnototherwisespecified.



Expression



Getsorsetstheexpressionusedtofilter

rows,calculateacolumn'svalue,orcreate

anaggregatecolumn.



Ordinal



Getsthenumericalpositionofthecolumn

intheColumnscollectionmaintainedby

theDataTable.



ReadOnly



Determinedifthiscolumncanbemodified

oncearowhasbeenaddedtothetable.

Thedefaultisfalse.



Table



GetstheDataTablethatcontainsthis

DataColumn.

Getsorsetsavalueindicatingwhetherthe



Unique



valuesineachrowofthecolumnmustbe

uniqueorifrepeatingvaluesare

permissible.Ifacolumnisassigneda

primarykeyconstraint,theUniqueproperty

shouldbesettotrue.



BuildingaDataColumn

ToillustratethebasicuseoftheDataColumn,assumeyouneedtomodel

acolumnnamedFirstName,whichinternallymapstoanarrayof

characters.



Furthermore,assumethiscolumn(forwhateverreason)mustberead

only.Programmatically,youcanwritethefollowinglogic:

protectedvoidbtnColumn_Click(objectsender,System.EventArgs

{

//BuildtheFirstNamecolumn.

DataColumncolFName=newDataColumn();

//Setabunchofvalues.

colFName.DataType=Type.GetType("System.String");

colFName.ReadOnly=true;

colFName.Caption="FirstName";

colFName.ColumnName="FirstName";



//Getabunchofvalues.

stringtemp="Columntype:"+colFName.DataType

"Readonly?"+colFName.ReadOnly

"Caption:"+colFName.Caption+"\n"+

"ColumnName:"+colFName.ColumnName

"Nullsallowed?"+colFName.AllowDBNull

MessageBox.Show(temp,"Columnproperties");

}

ThisgivestheresultshowninFigure13-3.



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

Appendix A: Data Access with ADO.NET

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

×