Tải bản đầy đủ - 0 (trang)
Chapter 18: Getting Started with ADO.NET

Chapter 18: Getting Started with ADO.NET

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

connectiontoanAccessdatabaseonyoursystem,you'llcreateadatasetthat

representsasubsetofusefulfieldsandrecordsfromadatabasetable,and

you'llusetheDatasetDesignerandDataSourceswindowtoexaminedataset

membersandcreateboundobjectsonyourforms.You'llalsolearnhowtouse

TextBoxandMaskedTextBoxcontrolstopresentdatabaseinformationtoyour

user,andyou'lllearntowriteSQLSELECTstatementsthatfilterdatasets(and

thereforewhatyouruserseesanduses)ininterestingways.

UpgradeNotes:MigratingVisualBasic6CodetoVisualBasic2005

ThefeaturesinVisualStudiorelatedtodatabaseprogramminghave

changedsignificantlyineachrecentreleaseofthesoftware.Although

continuallylearningnewtechniquescanbeasourceoffrustration,the

rapidpaceofchangecanbeexplainedpartiallybytherelativenewness

ofdistributedandmultiple-tierdatabaseapplicationprogrammingin

Windows,aswellastechnicalinnovationsthatarebeyondthecontrolof

theVisualStudiodevelopmentteam.Ifyou'reexperiencedwith

MicrosoftVisualBasic.NET2003,you'llnoticeseveralnewwindows

andtoolsinVisualStudio2005,althoughtheunderlyingdatasetmodel

introducedwithADO.NETisstillthesame.(MicrosoftADO.NET1.1

hasbeenupgradedtoMicrosoftADO.NET2.0withthisrelease.)If

you'reexperiencedwithMicrosoftVisualBasic6,you'llnoticemany

newfeaturesinMicrosoftVisualBasic2005,includingthefollowing:

ADO.NET,firstintroducedinMicrosoftVisualStudio.NET2002,

isthestandarddatamodelforallprogramsinVisualStudio2005,

includingMicrosoftVisualBasic,MicrosoftVisualC++,Microsoft

VisualJ#,andMicrosoftVisualC#.ThisversionofADO.NET

offersawiderrangeofdataaccesspossibilitiesthanitspredecessors

andisbasedonmorerecentMicrosoftdataaccesstechnology.

TheVisualBasic6RemoteDataObjects(RDO)andActiveXData

Objects(ADO)dataaccessmodelshavebeenreplacedby

ADO.NET.

InVisualBasic6,databaseinformationisrepresentedinaprogram

bytherecordsetobject.InVisualBasic2005,databaseinformation

isrepresentedbythedatasetobject,adisconnectedimageofthe



databasetableyou'reaccessing.

TheVisualBasic6DataandADODatacontrolsarenolonger

availableinVisualStudio2005.Todisplaydataonaform,you

typicallycreateadatasetbyusingtheDataSourceConfiguration

Wizardandthenaddboundcontrolstoyourformtodisplay

informationfromthedataset.IfyouusetheDataSourceswindowto

dothis,anavigationtoolbarisaddedautomatically.

TheinternaldataformatofADO.NETisExtensibleMarkup

Language(XML),makingiteasiertouseexistingXMLdata

sourcesandtouseADO.NETinprogramsdesignedfortheWeb.



DatabaseProgrammingwithADO.NET

Adatabaseisanorganizedcollectionofinformationstoredinafile.Youcan

createpowerfuldatabasesbyusinganyofavarietyofdatabaseproducts,

includingMicrosoftAccess,MicrosoftSQLServer,Oracle,andParadox.

YoucanalsostoreandtransmitdatabaseinformationbyusingXML,afile

formatdesignedforexchangingstructureddataovertheInternetandinother

settings.

Creatingandmaintainingdatabaseshasbecomeanessentialtaskforall

majorcorporations,governmentinstitutions,non-profitagencies,andmost

smallbusinesses.Richdataresources—forexample,customeraddresses,

manufacturinginventories,accountbalances,employeerecords,donorlists,

andorderhistories—havebecomethelifebloodofthebusinessworld.

VisualStudio2005isn'tdesignedforcreatingnewdatabases,butratherfor

displaying,analyzing,andmanipulatingtheinformationinexisting

databases.AlthoughpreviousversionsofVisualStudioandVisualBasic

havealsoprovidedthiscapability,VisualStudio2005offersanenhanced

datamodelcalledADO.NET2.0thatyoucanusetoworkwithaneven

greaternumberofdatabaseformatsandaccessscenarios.Inparticular,

ADO.NEThasbeendesignedforInternetuse,meaningthatitusesthesame

methodforaccessinglocal,client-server,andInternet-baseddatasources.As

atestimonytoitsgoalofmakingADO.NETagreattechnologyfor

manipulatingdatabasesovertheInternet,MicrosofthasmadeXML—a

standarddefinedbytheWorldWideWebConsortium—theinternaldata

formatofADO.NET.UsingXMLinthiswaymakesADO.NETeasierto

utilizewithexistingInternetdatasources,anditmakesiteasierforsoftware

vendorstowriteadapters,or“providers,”thatconvertthird-partydatabase

formatstobecompatiblewithADO.NET.



DatabaseTerminology

WhenworkingwithdatabasesandADO.NET,it'simportanttounderstand

somebasicdatabaseterminology.

Afield(alsocalledacolumn)isacategoryofinformationstoredina

database.Typicalfieldsinacustomerdatabasemightcontaincustomer



names,addresses,phonenumbers,andcomments.Alltheinformationabout

aparticularcustomerorbusinessiscalledarecord(lesscommonlycalleda

row).Whenadatabaseiscreated,informationisenteredinatableoffields

andrecords.Recordscorrespondtorowsinthetable,andfieldscorrespond

tocolumns,asshownhere:



Arelationaldatabasecanconsistofmultiplelinkedtables.Ingeneral,most

ofthedatabasesthatyouconnecttofromVisualStudiowillprobablybe

relationaldatabasesthatcontainmultipletablesofdataorganizedarounda

particulartheme.

InADO.NET,variousobjectsareusedtoretrieveandmodifyinformationin

adatabase.Thefollowingillustrationshowsanoverviewoftheapproach

thatwillbecoveredinmoredetailinthischapter:



Firstaconnectionismade,whichspecifiesconnectioninformationaboutthe

databaseandcreatessomethingforothercontrolsandcomponentstobindto.

NexttheDataSourcesConfigurationWizardcreatesadataset,whichisa

representationofoneormoredatabasetablesyouplantoworkwithinyour

program.(Youdon'tmanipulatetheactualdata,butratheracopyofit.)The

DataSourcesConfigurationWizardalsoaddsanXMLschemafiletoyour

projectandassociatesatableadapteranddatanavigatorwiththedatasetto

handleretrievingdatafromthedatabase,postingchanges,andmovingfrom

onerecordtothenextinthedataset.Youcanthenbindinformationinthe

datasettocontrolsonaformbyusingtheDataSourceswindowor

DataBindingspropertysettings



WorkingwithanAccessDatabase

Inthefollowingsections,you'lllearnhowtousetheADO.NET2.0data

accesstechnologyinVisualBasic2005.You'llgetstartedbyusingtheData

SourceConfigurationWizardtoestablishaconnectiontoadatabasenamed

Students.mdbthatIcreatedinMicrosoftAccess2002/2003format.

Students.mdbcontainsvarioustablesofacademicinformationthatwouldbe

usefulforateacherwhoistrackingstudentcourseworkoraschool

administratorwhoisschedulingrooms,assigningclasses,orbuildingatime

schedule.You'lllearnhowtocreateadatasetbasedonatableofinformation

intheStudentsdatabase,andyou'lldisplaythisinformationonaWindows

form.Whenyou'vefinished,you'llbeabletoputtheseskillstoworkinyour

owndatabaseprojects.

TIP



AlthoughthesampleinthischapterusesaMicrosoftAccessdatabase,you

don'thavetohaveAccessinstalled.VisualStudioandADO.NETincludethe

necessarysupporttounderstandtheAccessfileformat,aswellasother

formats.IfyoudecidetoopenthedatabaseinAccess,you'llfindthat

Students.mdbisinAccess2002/2003format.Ihavealsoincludedthefilein

Access2000format(Students_2000format.mdb)andAccess1997format

(Students_97format.mdb)sothatyoucanexperimentwiththesample

databaseinAccessevenifyouhaveanolderversion.



EstablishaconnectionbyusingtheDataSourceConfiguration

Wizard

1. StartVisualStudio,andcreateanewVisualBasicWindows

ApplicationprojectnamedMyADOForm.

AnewprojectappearsintheIDE.

2. OntheDatamenu,clicktheAddNewDataSourcecommand.

TheDataSourceConfigurationWizardappearsinthedevelopment

environment,asshownhere:



TheDataSourceConnectionWizardisanewfeaturewithintheVisual

Studio2005IDEthatautomaticallypreparesyourVisualBasicprogram

toreceivedatabaseinformation.Thewizardpromptsyouforthetypeof

databasethatyouwillbeconnectingto(alocalorremotedatabase,

Webservice,orcustomdataobjectthatyouhavecreated),establishesa

connectiontothedata,andthencreatesadatasetwithintheprogramto

holdspecificdatabasetablesandfields.Theendresultisthatthe

wizardopenstheDataSourceswindowandfillsitwithavisual

representationofeachdatabaseobjectthatyoucanuseinyour

program.

3. ClicktheDatabaseiconintheDataSourceConfigurationWizard,and

thenclickNext.

Thewizarddisplaysascreenthathelpsyouestablishaconnectionto

yourdatabasebybuildingastatementcalledaconnectionstring.A

connectionstringcontainstheinformationthatVisualStudioneedsto

openandextractinformationfromadatabasefile.Thisincludesapath



nameandfilename,butalsopotentiallysensitivedatasuchasa

usernameandpassword.Forthisreason,theconnectionstringistreated

carefullywithintheDataSourceConnectionWizard,andyoushould

takecaretoprotectitfromunauthorizedaccessasyoucopyyoursource

filesfromplacetoplace.

4. ClicktheNewConnectionbutton.

ThefirsttimethatyouclicktheNewConnectionbutton,theChoose

DataSourcedialogboxappears,promptingyoutoselectthedatabase

formatthatyouplantouse.IfyouseetheAddConnectiondialogbox

insteadoftheChooseDataSourcedialogbox,itsimplymeansthat

yourcopyofVisualStudiohasalreadybeenconfiguredtofavora

particulardatabaseformat.Noproblem;simplyclicktheChangebutton

intheAddConnectiondialogbox,andyou'llseethesamethingthat

first-timewizarduserssee,exceptthatthetitlebarreadsChangeData

Source,asshowninthefollowingillustration:



TheChange/ChooseDataSourcedialogboxistheplacewhereyou

selectyourpreferreddatabaseformat,whichVisualStudiousesasthe

defaultformat.Inthischapter,you'llselecttheMicrosoftAccess

format,butnotethatyoucanchangethedatabaseformattooneofthe

otherchoicesatanytime.Youcanalsoestablishmorethanone

databaseconnection—eachtoadifferenttypeofdatabase—withina

singleproject.

5. ClickMicrosoftAccessDatabaseFile,andthenclickOK.



TheAddConnectiondialogboxappears,asshowninthefollowing

illustration:



Nowyou'llspecifythelocationandconnectionsettingsforyour

database,sothatVisualStudiocanbuildavalidconnectionstring.

6. ClickBrowse.

TheSelectMicrosoftAccessDatabaseFiledialogboxappears,which

functionslikeanOpendialogbox.

7. Browsetothec:\vb05sbs\chap18folder,clicktheStudentsdatabase,

andthenclickOpen.

YouhaveselectedtheAccessdatabasein2002/2003formatthatIbuilt

todemonstratehowdatabasefieldsandrecordsaredisplayedwithina

VisualBasicprogram.TheAddConnectionsdialogboxappearsagain

withthepathnamerecorded.Idon'trestrictaccesstothisfileinany

way,soausernameandpasswordarenotnecessarywithStudents.mdb.

However,ifyourdatabaserequiresausernameand/orpasswordforuse,

youcanspecifyitnowintheUserNameandPasswordboxes.These

valuesarethenincludedintheconnectionstring.



8. ClicktheTestConnectionbutton.

VisualStudioattemptstoopenthespecifieddatabasefilewiththe

connectionstringthatthewizardhasbuiltforyou.Ifthedatabaseisin

arecognizedformatandtheusernameandpasswordentries(ifany)are

correct,youseethefollowingmessage:



9. ClickOKtoclosethemessagebox,andthenclickOKtoclosetheAdd

Connectiondialogbox.

VisualStudiodisplaystheDataSourceConfigurationWizardagain.

10. Clicktheplussign(+)nexttotheConnectionStringiteminthedialog

boxtodisplayyourcompletedconnectionstring.

Yourwizardpagelookssimilartothefollowing:



Theconnectionstringidentifiesaprovider(alsocalledamanaged

provider)namedMicrosoft.Jet.OLEDB.4.0,whichisanunderlying

databasecomponentthatunderstandshowtoconnecttoadatabaseand

extractdatafromit.ThetwomostpopularprovidersofferedbyVisual

StudioareMicrosoftJetOLEDBandMicrosoftSQL,butthird-party

providersareavailableformanyoftheotherpopulardatabaseformats.

11. ClicktheNextbutton.

Thewizarddisplaysanalertmessageindicatingthatanewlocal

databasehasbeenselected,andyouareaskedifthedatabaseshouldbe

copiedtoyourprojectfolders.(Thismessageonlyappearsthefirsttime

thatyoumakeaconnectiontoalocaldatabasefile.Ifyouarerepeating

thisexercise,youprobablywon'tseethemessage.)

12. ClickNotoavoidmakinganextracopyofthedatabaseatthistime.

Youarenotcommerciallydistributingthisproject;itisonlyasample

program,andanextracopyisnotneeded.



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

Chapter 18: Getting Started with ADO.NET

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

×