Tải bản đầy đủ - 0 (trang)
Lesson 1: Accessing Data with ADO.NET

Lesson 1: Accessing Data with ADO.NET

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

Thedataprovider.ThisconsistsoftheConnectionobjectandcommand

objectsthatcreatethein-memoryrepresentationofthedata.

Thedataset.Thisisthein-memoryrepresentationofthetablesand

relationshipsthatyouworkwithinyourapplication.

Thedataproviderlayerprovidesabstractionbetweenthephysicaldatastoreand

thedatasetyouworkwithincode.Afteryou'vecreatedthedataset,itdoesn't

matterwhereitcomesfromorwhereitisstored.Thisarchitectureisreferredto

asdisconnectedbecausethedatasetisindependentofthedatastore.

Figure5-1showstheADO.NETobjectmodelinaction.

Figure5-1

TheConnectionandcommandobjects

TherearetwotypesofdatabaseconnectioninADO.NET:

UseanOleDbConnectionobjecttoconnecttoalocaldatabase.OLEdatabase

connectionsusetheOleDbDataAdapterobjecttoperformcommandsand

returndata.

UseaSqlDbConnectionobjecttoconnecttoaserverdatabase.SQLdatabase

connectionsusetheSqlDbDataAdapterobjecttoperformcommandsand

returndata.

Inadditiontothesedatabaseconnections,youcanaccessXMLfilesdirectly

fromdatasetsusingtheDataSetobject'sReadXMLandWriteXMLmethods.

XMLfilesarestaticrepresentationsofdatasets.ADO.NETusesXMLforall

datatransferacrosstheInternet.

ADO.NETprovidesitsobjects,properties,andmethodsthroughthethreenamespacesdescribedinTable5-1.TheSystem.Data.SqlClientand

System.Data.OleDbnamespaceslistedinthetableprovideequivalentfeatures

forSQLandOLEdatabases,respectively.



Namespace

System.Data



Table5-1

ADO.NETNamespaces

Provides

Classes,types,andservicesforcreatingandaccessing



datasetsandtheirsubordinateobjects

ClassesandtypesforaccessingMicrosoftSQLServer

System.Data.SqlClient

databases

System.Data.OleDb

ClassesandtypesforaccessingOLEdatabases

Whenworkingwithdatabasesincode,youneedtoaddthefollowingImportsor

usingdeclarationsatthetopofyourcodemodule:



VisualBasic.NET

ImportsSystem.Data

'ForSQLdatabaseconnections.

ImportsSystem.Data.SqlClient

'ForOLEDBdatabaseconnections.

ImportsSystem.Data.OleDb



VisualC#

usingSystem.Data

//ForSQLdatabaseconnections.

usingSystem.Data.SqlClient

//ForOLEDBdatabaseconnections.

usingSystem.Data.OleDb



ToaccessadatabasethroughADO.NET,followthesesteps:

1. Createaconnectiontothedatabaseusingaconnectionobject.

2. InvokeacommandtocreateaDataSetusinganadapterobject.

3. UsetheDataSetobjectincodetodisplaydataortochangeitemsinthe

database.

4. InvokeacommandtoupdatethedatabasefromtheDataSetusingan

adapterobject.

5. Closethedatabaseconnectionifyouexplicitlyopeneditinstep2usingthe

Openmethod.InvokingcommandswithoutfirstinvokingtheOpenmethod

implicitlyopensandclosestheconnectionwitheachrequest.

Thefollowingsectionsdiscusseachofthesestepsinmoredetail.



ConnectingtoaDatabase



UsetheServerExplorertoconnecttoadatabaseinVisualStudio.

ToconnecttoadatabaseintheVisualStudiodesignenvironment,followthese

steps:

1. FromtheViewmenu,chooseServerExplorer.VisualStudiodisplaysthe

ServerExplorerwindow.

2. IntheServerExplorer,clickConnectToDatabaseToolbar.VisualStudio

.NETdisplaystheDataLinkPropertiesdialogbox,asshowninFigure5-2.

Figure5-2

TheDataLinkpropertiesdialogbox

3. Clickthedialog'sProvidertabtoselectthetypeofdatabaseforthe

connection.BydefaultthedatabaseproviderisMicrosoftOLEDB

ProviderforSQLServer.Thatisthecorrectselectionifyourdatabaseis

runningunderMicrosoftSQLServer.Toaccessadifferenttypeofdatabase,

selecttheappropriateprovider.Forinstance,toaccessaMicrosoftAccess

2000databasedirectly,selectMicrosoftJet4.0OLEDBProvider.

4. ClicktheConnectiontabtospecifythedatabasetoconnectto.Changing

thedatabaseproviderinstep3changestheconnectionsettings,asshownin

Figure5-3.

Figure5-3

TheConnectiontab

5. EntertheconnectionsettingsandclickTestConnectiontomakesureyour

settingarecorrect.ClickOKwhentheconnectionsucceeds.VisualStudio

addsthedataconnectiontotheServerExplorer,asshowninFigure5-4.

Figure5-4

TheServerExplorer

6. ClickingtheplussignsintheServerExplorerexpandsitems.Toviewthe

tablesinadataconnection,expandtheitemsunderthedataconnectionand

thenexpandtheitemsunderTables.VisualStudiodisplaysthetables,as

showninFigure5-5.



Figure5-5

ExpandeditemsintheServerExplorer

7. Toaddadataitemtoyourapplication,drag-and-droptheitemfromthe

ServerExplorertoyourWebform.Forinstance,dragtheContactstable

showninFigure5-5totheWebform.Whenyoudropthetableontothe

Webform,VisualStudiocreatesconnectionandadapterobjectswiththe

appropriatesettings,asshowninFigure5-6.

Figure5-6

Connectionandadapterobjects

WebapplicationsrunusingtheASPNETuseraccount.TheSQL

databaseadministratorwillhavetosetupthisaccountandgrant

itpermissionsbeforeyourWebapplicationwillhaveaccesstoa

SQLdatabase.ForAccessdatabases,youmustgrant

permissionsonthedatabasefiletotheASPNETuseraccount

usingWindowsfilesecuritysettings.



CreatingaDataSet

Usethedataconnectionandadapterobjectscreatedinstep7ofthepreceding

sectiontocreateadataset.

TocreateadatasetinDesignmode,followthesesteps:

1. Right-clickthedataadapterobjectandselectGenerateDatasetfromthe

pop-upmenu.VisualStudiodisplaystheGenerateDatasetdialogbox,as

showninFigure5-7.

Figure5-7

TheGenerateDatasetdialogbox

2. SelectthetablestoaddtothedatasetandclickOK.VisualStudiocreatesa

newDataSetobjectandaddsittotheWebform.

ToviewthedatainthedatasetinDesignmode,right-clicktheDataSetobject,

andthenselectViewSchemafromthepop-upmenu.VisualStudiodisplaysthe



datasetintheXMLDesignerwindow,asshowninFigure5-8.

Figure5-8

DatasetschemainDesignmode



DisplayingaDataSet

TodisplaythedatasetontheWebformatruntime,followthesesteps:

1. AddacontroltotheWebformtodisplaythedata.Forinstance,adda

DataGridcontroltotheWebform.

2. Setthedatasetasthedatasourceforthecontrol.Forinstance,forthe

DataGridcontrol,clickthePropertyBuilderlinkonthePropertiesWindow,

settheDataSourcepropertytotheDataSetobject,andsettheDataMember

propertytoatableinthedataset,asshowninFigure5-9.

Figure5-9

DatabindingonaDataGrid

3. Setthecolumnstodisplayinthecontrol.FortheDataGridcontrol,clickthe

ColumnsiteminthePropertiesdialogbox,deselecttheCreateColumns

AutomaticallyAtRunTimecheckbox,andthenaddthecolumnstodisplay

fromtheAvailableColumnslist,asshowninFigure5-10.ClickOKwhen

youaredone.

Figure5-10

AddingcolumnstodisplayintheDataGrid

4. AddcodetotheWebform'sPage_Loadeventproceduretofillthedataset

fromthedataadapterandtobindthedatafromtheDataSetobjecttothe

control.Forexample,thefollowingcodedisplaysthedataintheDataGrid

controlcreatedintheprevioussteps:



VisualBasic.NET

PrivateSubPage_Load(ByValsenderAsSystem.Object,

ByValeAsSystem.EventArgs)HandlesMyBase.Load

'Fillthedataset.

SqlDataAdapter1.Fill(DataSet1)



'UpdatetheDataGrid.

DataGrid1.DataBind()

EndSub



VisualC#

privatevoidPage_Load(objectsender,System.EventArgse)

{

//Fillthedataset.

sqlDataAdapter1.Fill(DataSet1);

//UpdatetheDataGrid.

DataGrid1.DataBind();

}



5. Runtheapplication.Whenthepageloads,thedatasetisdisplayed,as

showninFigure5-11.

Figure5-11

TheDataGridatruntime

Becauseyouarefillingthedatasetandbindingthedatatothe

DataGridcontrolinthePage_Loadevent,youdon'tneedto

maintainstateinformationfortheDataGridcontrol.Turningoff

stateinformationimprovesperformancebecausethedataonthe

DataGriddoesnothavetobesavedtothepage'sViewState

betweenrequests.SettheDataGrid'sEnableViewStateproperty

toFalsetoturnoffstatemaintenanceforthecontrol.



ChangingRecordsinaDatabase

TheDataSetisthecentralobjectinADO.NET.Anyadditions,deletions,or

changestorecordsinadatabasearegenerallydonethroughaDataSetobject.

TochangerecordsthroughaDataSetobject,followthesesteps:

1. GetaDataSetobjectasdescribedintheprecedingsections.

2. ModifytheDataSet.

3. UpdatethedatabasefromtheDataSetbycallingthedataadapter'sUpdate



method.

YouusetheTables,Rows,andColumnscollectionstogettodataitemsina

DataSet,asshowninFigure5-12.

Figure5-12

DataSetcollections



HowADO.NETReferstoObjects

Whenyoucreateconnection,adapter,anddatasetobjectsinDesignmode,you

enabledatatypingforthoseobjects.Thismeansthatyoucanusethespecific

namesfromthedatabaseschematoidentifytables,rows,andfields.Thisisabig

changefromADO,whichprovidedonlyuntypedreferencestodataobjects.

Thefollowingequivalentlinesofcodeshowatypedreferencevs.anuntyped

referencetoanobjectfromadatabase:



VisualBasic.NET

'TypedreferencetotheContactstable'sHomePhonecolumn.

DataSet1.Contacts.HomePhoneColumn.Caption="@Home"

'UntypedreferencetotheContactstable'sHomePhonecolumn.

DataSet1.Tables("Contacts").Columns("HomePhone").Caption="@Home"



VisualC#

//TypedreferencetotheContactstable'sHomePhonecolumn.

DataSet1.Contacts.HomePhoneColumn.Caption="@Home";

//UntypedreferencetotheContactstable'sHomePhonecolumn.

DataSet1.Tables["Contacts"].Columns["HomePhone"].Caption="@Home";



Thefirstlineintheprecedingcodeisnotonlyeasiertotypeandtoread,butalso

muchlesserrorprone,sinceVisualStudiochecksdatatypesasyouwork,

flagginganytyposasunrecognizedreferences.

Ingeneral,youshouldusetypedreferenceswhenworkingwithdataobjects.The

exceptiontothisruleoccurswhenyoudon'tknowthespecificobjectyouare

workingwith.Usually,thissituationoccurswhenthedatasourceissuppliedat



runtimeratherthanatdesigntime.

TypeinformationfordataobjectscomesfromtheXMLSchemathatVisual

StudiogenerateswhenyoucreateadatasetinDesignmode.

Toviewtypeinformationforadataset,right-clickthedatasetintheDesign

windowandselectViewSchemafromthepop-upmenu.VisualStudiodisplays

thedatasetintheXMLDesigner,asshowninFigure5-13.

Figure5-13

Viewingtypeinformation

YoucanusetheXMLDesignertoaddelements,specifyuniquekeys,andview

orchangethedatatypesofelementsinadataset.



Adding,Changing,andDeletingRows

UsetheRowscollectiontoadd,change,ordeleterowsintheDataSet'sTable

object.Toaddarecordtoadataset,createanewRowobjectandaddittothe

DataSet'sRowscollection,asshownbythefollowingcode:



VisualBasic.NET

'Usesconnection,adapter,anddatasetcreatedinDesignmode.

PrivateSubbutAddRow_Click(ByValsenderAsSystem.Object,_

ByValeAsSystem.EventArgs)HandlesbutAddRow.Click

'CreateanewrowobjectfortheContactstable.

DimrowNewAsDataSet1.ContactsRow=DataSet1.Contacts.NewRow

'Adddatatothecolumnsintherow.

rowNew.ContactID=42

rowNew.FirstName="Danielle"

rowNew.LastName="Tiedt"

rowNew.WorkPhone="(111)555-1212"

'Addtherowtothedataset.

DataSet1.Contacts.Rows.Add(rowNew)

EndSub



VisualC#

//Usesconnection,adapter,anddatasetcreatedinDesignmode.

privatevoidbutAddRow_Click(objectsender,System.EventArgse)



{

//CreateanewrowobjectfortheContactstable.

DataSet1.ContactsRowrowNew=

(DataSet1.ContactsRow)DataSet1.Contacts.NewRow();

//Adddatatothecolumnsintherow.

rowNew.ContactID=42;

rowNew.FirstName="Danielle";

rowNew.LastName="Tiedt";

rowNew.WorkPhone="(111)555-1212";

}



Tochangearowinadataset,getaRowobjectfromthetableusingtheFindBy

method,andthenmakechangestothefieldsintherow,asshownbythe

followingcode:



VisualBasic.NET

'Usesconnection,adapter,anddatasetcreatedinDesignmode.

PrivateSubbutChangeRow_Click(ByValsenderAsSystem.Object,_

ByValeAsSystem.EventArgs)HandlesbutChangeRow.Click

'Declarearowobject.

DimrowChangeAsDataSet1.ContactsRow

'Gettherowtochangeusingtheprimarykey.

rowChange=DataSet1.Contacts.FindByContactID(42)

'Changeafieldintherow.

rowChange.WorkPhone="(111)555-9000"

EndSub



VisualC#

//Usesconnection,adapter,anddatasetcreatedinDesignmode.

privatevoidbutChangeRow_Click(objectsender,System.EventArgse)

{

//Declarearowobject.

DataSet1.ContactsRowrowChange;

//Gettherowtochangeusingtheprimarykey.

rowChange=DataSet1.Contacts.FindByContactID(42);

//Changeafieldintherow.

rowChange.WorkPhone="(111)555-9000";

}



Todeletearowinadataset,getaRowobjectfromtheTableusingtheFindBy

method,andthendeletetherowusingtheRowobject'sDeletemethod,as

shownhere:



VisualBasic.NET

'Usesconnection,adapter,anddatasetcreatedinDesignmode.

PrivateSubbutDeleteRow_Click(ByValsenderAsSystem.Object,_

ByValeAsSystem.EventArgs)HandlesbutDeleteRow.Click

'Declarearowobject.

DimrowDeleteAsDataSet1.ContactsRow

'Gettherowtodelete

rowDelete=DataSet1.Contacts.FindByContactID(42)

'Deletetherow.

rowDelete.Delete()

EndSub



VisualC#

//Usesconnection,adapter,anddatasetcreatedinDesignmode.

privatevoidbutDeleteRow_Click(objectsender,System.EventArgse)

{

//Declarearowobject.

DataSet1.ContactsRowrowDelete;

//Gettherowtodelete

rowDelete=DataSet1.Contacts.FindByContactID(42);

//Deletetherow.

rowDelete.Delete();

}



UpdatingtheDatabasefromtheDataSet

Usethedataadapter'sUpdatemethodtoupdatethedatabasewithchangesfrom

aDataSetobject.Youwillusuallywanttodothisafterallofthecontrolevents

onapagehavebeenprocessed;therefore,theUpdatemethodisusuallycalled

fromthePage_PreRenderevent,asshownhere:



VisualBasic.NET

'Usesconnection,adapter,anddatasetcreatedinDesignmode.

PrivateSubPage_PreRender(ByValsenderAsObject,_

ByValeAsSystem.EventArgs)HandlesMyBase.PreRender

'Updatethedatabasewithchangesfromthedataset.

SqlDataAdapter1.Update(DataSet1)

EndSub



VisualC#

//Usesconnection,adapter,anddatasetcreatedinDesignmode.

privatevoidPage_PreRender(objectsender,System.EventArgse)

{

//Updatethedatabasewithchangesfromthedataset.

sqlDataAdapter1.Update(DataSet1);

}



Whenyouupdateadatabasefromadataset,ADO.NETfollowsthesesteps:

1. DeterminesthechangestothedatasetbycheckingeachDataRowobject's

RowStateproperty.PossiblevaluesareAdded,Deleted,Modified,

Unchanged,orDetached.

2. Invokestheadapterobject'sInsertCommand,DeleteCommand,or

UpdateCommandpropertiestomaketherequiredchangesinthedatabase.

3. ResetstheupdatedDataRowobjects'RowStatepropertiestoUnchanged.

Theadapterobject'sInsertCommand,DeleteCommand,and

UpdateCommandpropertiesaregeneratedautomaticallyfromtheadapter

object'sSelectCommandwhenyoucreateadatasetfromadataadapterin

Designmode.EachofthesepropertiesrepresentsanOleCommandor

SqlCommandobject.Commandobjectshavethefollowingpropertiesthat

determinehowthecommandisexecuted:

TheCommandTextpropertycontainstheSQLstatementorthestored

procedurenametoperformthecommand.

TheCommandTypepropertydetermineshowthecommandisperformed

bythefollowingpossiblesettings:

TheTextsettingexecutesthecommandasaSQLstatement.(Thisisthe

default.)

TheStoredProceduresettingexecutesthecommandasaprocedure

storedinthedatabase.

TheTableDirectsettingreturnstheentiretable.Thissettingappliesonly

toOLEDB.NETdataproviders.

Youcanchangethecontentsofthedatasetandhowthedatasetisupdated

bychangingtheSQLstatementsusedbythesecommandobjects.

Toviewormodifythesecommands,followthesesteps:



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

Lesson 1: Accessing Data with ADO.NET

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

×
x