ASP.NET的Web数据库访问技术
ASP.NET的Web数据库访问技术
王进
GuilinUniversityofElectronicTechnologyTeachingPractice&ExperimentDepartment,China
桂林电子工业教学实践与实验系,中国
access_wj@I.VIIII.net
access_wj@I.VIIII.net
摘要:
本文介绍了ASP.NET的Web数据库访问的原理,阐述了III种连接方法和两种访问模型,对ASP.NET网页与数据库,然后分析和比较了使用ADO.NET的数据库访问技术的各种方法.同时,提供了I.些实用的代码.ASP.NET是目前I.个访问WEB数据库的理想选择.
关键字:ASP.NET;ADO.NET;Web数据库;数据访问
I..引言
数据访问是Web应用程序开发的关键问题.I.般企业应用程序需要数据驱动的Web页面,开发人员必须从不同的数据格式的数据源进行快速访问.当前的Windows环境下,有各种不同的Web数据库的访问技术.如:CGI(公共网关接口).ADC(先进数据库连接器).IDC(Internet数据库连接器).Java/JDBC.ASP和ASP.NET(ActiveServerPage)等.
ASP.NET是I.个由微软公司推出的由ASP发展而来的新I.代的Web应用程序开发技术,它为用户提供了I.个完整的视觉的开发环境.它紧密结合.NET框架并提供了I.种模块化的设计方法,多语言支持,代码与HTML设计是分开的.因此它的结构清晰.可读性高和执行效率高等优点.
ADO.NET是I.种微软.NET平台的不断更新和发展的数据库访问技术.它拥有I.个全新的设计理念,并在原有ADO基础上具有明显的创新.无论数据源是来自于何种数据库,它都 *好棒文|www.hbsrm.com +Q: 3_5_1_9_1_6_0_7_2
可以有效地进行访问.它是应用程序与数据库之间的重要桥梁.
在使用ADO.NET技术访问数据库的实现过程中,I.旦遇到对象模型或基本开发过程是自己不熟悉的,这通常导致技术故障.针对这I.事实,本文分析和探讨了在ASP.NET中如何访问数据库的技术.
II.访问原理
通过服务器端组件ADO.NET,ASP.NET实现Web数据库访问.ADO.NET为.Net框架提供优化的,面向网络的数据访问模型,它拥有它自己的XML格式和NET体系结构的ADO.NET接口.ADO.NET为应用程序提供了两种数据访问模式:连接模式和非连接模式.与传统的,非连接模式相比,增强了可靠性和稳定性.在这种模式中,I.旦应用程序从数据源中获得需要的数据,它会断开与原始数据源的连接,并以XML格式存储获得的数据.处理后,再和与原数据进行连接,并完成数据的更新.
ADO.NET包含两个核心组件:Dataset和NETFrameworkDataProvider.前者为非连接式结构的核心组件,实现了独立于任何数据源的数据访问和管理本地应用程序数据.后者是I.组包括Connection",Command",DataReader",DataAdapter"等有关对象的组件并提供了有关数据操作的方法,如数据的方法快速访问,只前进和只读访问.这其中,Connection"提供数据源的连接.Command"提供了获得数据.修改数据.运行存储过程和发送或检索参数信息的数据库命令.DataReader"提供了从数据源获得数据的高性能数据流,它是使用数据集连接数据源的桥梁.DataAdapter"使用Command"对象在数据源中执行SQL命令,它会载入数据到数据集中,使数据集的更新与数据源保持I.致.
III.连接方法
在I.个ASP.NET页面文件查询之前,插入.更新数据库,它应该首先与数据库建立I.个连接,然后做I.些相应的操作过程.
建立数据库连接的步骤是:
I..介绍相关的在页面文件的ADO.NET命名空间;
II.设置数据库连接参数;
III.根据连接参数,创建I.个数据库连接对象;
IV.执行数据库连接操作.
III.I..III种接线方式
ASP.NET通过ADO.NET访问数据库时有III种连接方式,第I.种,通过ADO.NET托管提供程序可以连接到任何ODBC;第II,通过ADO.NET托管提供程序可以连接到任何OLEDB数据中心;第III,通过SQL托管提供程序可以连接到MSSQLServer.I.般来说,在这III种方法中,SQL托管提供程序是效率最高的,其次是ADO.NET托管提供程序+OLEDB,最差的是ADO.NET托管提供程序+ODBC.
III.II.两种接入模式
ADO.NET根据不同形式的网站数据库提供了两种访问模式.I.个是流的从数据源读取的DataReader".另I.种是通过数据集来分离异构数据源.如果只想在网页上显示数据,很少需要操纵或改变它们,你可以通过使用ADO直接访问数据库.该模型利用SqlDataReader对象或OleDbDataReader对象来快速阅读.这些类等价于ADO快进指针(光标).他们与数据源保持I.个动态连接,但不能做任何改变.如果想从SqlDataReader或OleDbDataReader得到I.行数据, *好棒文|www.hbsrm.com +Q: 3_5_1_9_1_6_0_7_2
读"这个方法应该被采用.
如果想做I.个更复杂的交互访问,你应该通过ADO.NET使用DataSet对象.与传统的ADO技术相比,ADO.NET使用断开方法.那就是在ADO.NET中,无需使用游标与数据库建立I.个连接.相反,填充数据集(数据集)到从数据库中提取副本的信息中.如果数据集信息已经改变,在数据库中相应的信息不可改变.那就是,你可以很容易的改变而不用担心操纵数据,因为数据库连接是I.个不重要的.如果有必要,数据集可以被连接到原始数据源并应用于所有更改.
数据库访问的示意图:图I.
IV.ASP.NET数据库访问
通用数据库访问的方式主要有以下几种:
IV.I..使用通用数据访问方法
这是ADO.NET的标准程序.方法:通过采用简单对象模型,如连接",命令"和数据集"等,编写出可以连接到各种不同数据源的应用.IV.I.UsingCommonDataAccessMethods
示例代码如下:
OleDbConnectionConn=new
OleDbConnection(Provider=Microsoft.Jet.OLEDB.IV.0,"+
DataSource="+Server.MapPath(example.mdb"));
//connectionobject
Conn.Open();//openconnectionobject
OleDbCommandComm=newOleDbCommand(select*from
sample",Conn);
//querydatafromsample
OleDbDataReaderdr=Comm.ExecuteReader();
//Datareadobject
……
OleDbDataAdapterda=newOleDbDataAdapter(select*from
sample",Conn);
DataSetds=newDataSet();
Da.Fill(ds,sample");
dgid.DataSource=ds.Tables[sample"].DefaultView;
//
dgid.DataBind();
但事实上,可编程性和不同数据源的特点是V花VIII门,上面的方法使用了所有的数据源提供的共识"功能,.所以在这种方法中,数据源特定选项的优势将会丧失,不能提供访问和操纵各种数据库信息的最佳方法.
IV.II.使用基本的界面
通过接口(IDbConnection.IDbCommand.IDataReader等),代码将被封装在I.个具体到I.个特定的数据源的类中,所以独立于后端数据库服务器的剩下应用程序将受它的影响.通常情况下,接口的主要工作是:定义字符串的连接,打开和关闭连接,定义命令及相关参数,执行不同类型的命令,返回数据,对数据执行操作但不返回任何值.提供单向访问和对返回的数据集进行只读访问.
IV.III.专业数据访问类的准备
上述两种方法有I.定的局限性,I.个好的改善抽象水平的解决方案是,通过创建I.个特殊类来封装特定数据供应者的使用,并通过数据结构和与其他应用程序无关的层次来交换信息,如:特定的数据源,数据集的类型化,对象集合等.我们可以为每个支持在I.个特定程序集的数据源创建I.个特殊的类,并在需要的情况下,根据配置文件从应用程序加载它们.所以,如果想添加新数据源到应用程序中,你只需要在定义好的I.组通用接口规则中实现I.个新类目标.如果希望SQLServer作为数据源并提供支持,你可以做以下定义:
namespaceMYEXAMPIE{
publicclassSample:IDbSample{
publicDataTableGetSam(){
StringConnStr=
ConfigurationSettings.AppSettings[ConnStr"];
using(SqlConnectionconn=newSqlConnection(ConnStr)){
stringcmdString=SELECTID,nameFROMSample";
SqlCommandcmd=newSqlCommand(cmdString,conn);
SqlDataAdapterda=newSqlDataAdapter(cmd);
DataTabledt=newDataTable(Sample");
Da.Fill(dt);
returndt;}}
publicDataTableGetSamID(stringID){……}
publicboolInsertSam(){……}
……//Andotherachievedmethod
}}
实现IDbSample接口的类示例.我们只能创建I.个新类,当需要支持新的数据源时来实现这个接口.这种接口可以定义如下:
namespaceCommon{
publicinterfaceIDbSample{
DataTableGetSam();
DataTableGetSamID(stringID);
boolInsertSam();}}
其他类型的数据源类似于上面的代码,在这里,我们不会给不必要的细节.这种方法的优点是:高度的解耦,容易改变,适合团队开发.解耦的好处是容易测试.当测试时,我们可以模拟I.个数据访问层,独立测试业务逻辑,甚至可以模拟各种数据库错误,也可以单独测试数据访问层.
V.小结
在网站建设中,有I.些.NET的ASP.NET技术访问数据库的其他方法,通常,它是类似的.在实际的开发过程中,哪种方式会被选择?我们应该根据需要灵活选择.此外,通过数据控制封装功能,当访问和显示数据时,ASP.NET可以更灵活的控制数据,并减少所需的代码.从传统数据库到XML数据存储,各种数据源可以被连接到这些控制,并且所有的数据源可以以类似的格式来处理,大大减小了数据驱动应用程序开发的复杂性.目前,ASP.NET是I.个用于Web数据库访问的理想选择.
参考文献
I..Sun,Z.-J.,Lu,L.:AnImplementofWebDatabaseAccessApplicationsBasedonMidware
Technology.ComputerSystems&ApplicationsI.,VIIIVII–IX0(II00VIII)
II.Millett,S.:ProfessionalASP.NETDesignPatterns.Wrox(II0I.0)
III.Evjen,B.,Hanselman,S.,Rader,D.:ProfessionalASP.NETIII.VSPI.edn.InC#andVB.
Wrox(II00IX)
IV.Zhou,S.-X.:ResearchonDataAccessTechnologyBasedonADO.NETII.0.Computer
TechnologyandDevelopmentI.VIII,I.IVIV–I.IVVI(II00VIII)
附件II:外文原文(复印件)
WebDatabaseAccessTechnologyBasedonASP.NET
JinWang
GuilinUniversityofElectronicTechnologyTeachingPractice&ExperimentDepartment,China
access_wj@I.VIIII.net
Abstract:
ThisarticlepresentstheprincipleaboutWebdatabaseaccessbasedon
ASP.NET,expoundsthreekindsofconnectionmethodsandtwoaccessing
modelsthataboutASP.NETpageanddatabase,andthenanalyzesandcompares
variousmeansaboutusingADO.NETtechnologyondatabaseaccess.Inthe
meantime,providessomeutilitycodes.ASP.NETiscurrentlyanidealchoiceforvisitingWebdatabase.
Keywords:ASP.NET,Webdatabase,ADO.NET,dataaccess.
I.Introduction
Dataaccessisakeyissueonwebapplicationdevelopment.Generalbusinessapplicationneedsdata-drivenWebpages,developermustquicklyaccessthedatafromdifferentformatsdatasource.Underthecurrentwindowsenvironments,therearevarioustechnologiesonwebdatabaseaccess.Suchas:CGI(CommonGatewayInterface).ADC(AdvanceDatabaseConnector).IDC(InternetDatabaseConnector).Java/JDBC.ASPandASP.NET(ActiveServerPage)etc.
ASP.NETisanewgenerationtechnologyofwebapplicationdevelopmentthattheMicrosoftCompanylaunchesfollowingtheASP,andprovidesacompletevisual
developmentenvironmentforusers.Itcloselyintegrateswiththe.NETFrameworkandprovidesamodulardesignmethod,supportsformultipleprogramminglanguages,codeandHTMLdesignisseparated.Itismoreclearlystructure,morereadableandhighefficiency.
ADO.NETisanuptodatedatabaseaccesstechnologyattheMicrosoft.NET
platform.Ithasabrandnewdesignconcept,andhasasignificantinnovationsbasedontheoriginalADO.Nomatterwhichdatabasethedatasourcescomefrom,allofthemcanbeeffectivelyaccessed.Itisanimportantbridgebetweenapplicationsanddatabases.
DuringtheimplementationprocessofusingADO.NETtechnologytovisitdatabase,onaccountofunfamiliarwithobjectmodelandbasicdevelopmentoperation,usuallyleadtotechnicalfault.Inresponsetothisfact,thisarticleanalysesanddiscussesthetechnologyofdatabaseaccessinASP.NET.
IIAccessPrinciple
ThroughServer-sidecomponentADO.NET,ASP.NETrealizeswebdatabasevisiting.ADO.NETprovidesoptimized,facingwebdataaccessmodelforthe.NETframework,ithasitsownADO.NETinterfacebasedonXMLformatand.NETarchitecture.ADO.NETprovidestwodataaccessmodelsfortheapplication:connectionmodeandnon-connectionmode.Comparedwiththetraditional,non-connectionmodestrengthensthereliabilityandstability.Inthismode,oncetheapplicationobtainstherequireddatafromthedatasource,itwoulddisconnecttheconnectionwiththeoriginaldatasource,andstoretheobtainingdataintheformofXML.Afterhandling,itthenmadetheconnectionwiththeoriginaldataandcompletesthedataupdating.
ADO.NETincludestwocorecomponents:Datasetand.NETFrameworkdataprovider.Theformerisacorecomponentofoff-typestructure,whichrealizesdataaccessindependentlyofanydatasourceandmanageslocalapplicationdata.ThelatterisagroupcomponentincludingobjectsaboutConnection",Command",DataReader",DataAdapter",andprovidesmethodsaboutdatamanipulation,datafastaccess,forward-onlyandread-onlyaccess.Amongthis,Connection"providesconnectivitywiththedatasources.Command"providesdatabasecommandsusedforreturningdata,modifyingdata,runningstoredproceduresandsendingorretrievingparameterinformation.DataReader"provideshigh-performancedataflowfromdatasourceanditisabridgethatconnectsthedatasourcewithDataset.DataAdapter"usesCommand"objectstoexecuteSQLcommandinthedatasource,anditwouldloadthedataintotheDataset,makethechangestotheDatasetconsistentwiththedatasource.
IIICnnectionMethod
BeforeanASP.NETpagefilequery,insert,updatethedatabase,itshouldestablisha
connectionwiththedatabasefirst,andthendosomecorrespondingoperationprocess.
Thestepstoestablishdatabaseconnectionis:
I..IntroduceassociatedADO.NETnamespaceinthepagefile
II.Setdatabaseconnectionparameters
III.Accordingtotheconnectionparameters,createadatabaseconnectionobject
IV.Executedatabaseconnectionoperation
III.I.ThreeKindsofConnectionMode
TherearethreeconnectionwaysthatASP.NETvisitsdatabasethroughADO.NET,thefirstone,throughADO.NETManagedProvidercouldconnecttoanyODBC;thesecond,throughADO.NETManagedProvidercouldconnecttoanyOLEDBdatacenter;thethirdwaythroughSQLManagedProvidercouldconnecttoMSSQLServer.Generally,inthesethreemethods,SQLManagedProviderismostefficient,followedbyistheADO.NETManagedProvider+OLEDB,theworstoneisADO.NETManagedProvider+ODBC.
III.IITwoAccessModel
ADO.NETprovidestwoaccessingmodelsaccordingtodifferentformsofWebdatabase.OneisDataReader"thatreadfromdatasourcebasedonstream.AnotheristhroughtheDatasettoisolateheterogeneousdatasource.Ifonlywanttodisplaydataonawebpageandseldomneedtomanipulateorchangethem,youcandirectlyaccessthedatabasebyusingADO.NET.ThismodelutilizesSqlDataReaderobjectorOleDbDataReaderobjectforfastreading.TheseclassesareequivalenttoADOfastforwardpointer(cursor).Theykeepanactivityconnectionwithdatasource,butcannotmakeanychanges.IfwanttogetarowofdatafromsqIDataReaderorOleDbDataReader,theRead"methodshouldbeused.
Ifwanttodoamorecomplexinteractiveaccess,youshoulduseDataSetobjectthroughADO.NET.ComparedwiththetraditionalADOtechnology,ADO.NETusesdisconnectmethod.Thatis,intheADO.NET,createaconnectiontothedatabase
withoutusingcursors.Instead,filldataset(DataSet)withinformationcopiesextractedfromadatabase.Ifthedatasetinformationhasbeenchanged,thecorrespondinginformationindatabasewouldnotbechanged.Thatis,youcaneasilychangeandmanipulatedatawithoutworry,becausethedatabaseconnectionisnottheimportantone.Ifnecessary,theDatasetcanbeconnectedbacktotheoriginaldatasourcesandapplyallchanges.
Schematicdiagramofdatabaseaccess:Fig.I.
Fig.I..
IVASP.NETDatabaseAccess
Commondatabaseaccesswaybasicallyhasthefollowingkinds:
IV.I.UsingCommonDataAccessMethods
ThisisthestandardprocedureforADO.NET.Themethodis:byusingsimpleobject
model,suchasConnection",Command"andRecordset"etc,writeoutapplicationsthatcouldconnecttoallkindsofdifferentdatasources.
Samplecodeisasfollows:
OleDbConnectionConn=new
OleDbConnection(Provider=Microsoft.Jet.OLEDB.IV.0,"+
DataSource="+Server.MapPath(example.mdb"));
//connectionobject
Conn.Open();//openconnectionobject
OleDbCommandComm=newOleDbCommand(select*from
sample",Conn);
//querydatafromsample
OleDbDataReaderdr=Comm.ExecuteReader();
//Datareadobject
……
OleDbDataAdapterda=newOleDbDataAdapter(select*from
sample",Conn);
DataSetds=newDataSet();
Da.Fill(ds,sample");
dgid.DataSource=ds.Tables[sample"].DefaultView;
//
dgid.DataBind();
Butinfact,theprogrammabilityandfeaturesofvarietydatasourcesaremultifarious,andtheabovemethoduseCommonground"offunctionthatallthedatasourcehaveprovided.Sointhisapproach,theadvantageofdatasourcespecificoptionwillbelost,andcouldnotprovidethebestmethodofaccessingandmanipulatinginformationinvariousRDBMS.
IV.IIUsingBasicInterface
Throughinterface(IDbConnection.IDbCommand.IDataReaderetc),thecodewillbeencapsulatedinaclassspecifictoaparticulardatasource,sotherestoftheapplicationindependentoftheback-enddatabaseserverandwouldfromitseffects.Usually,themainworkofinterfaceis:defineconnectionstring,openandclosetheconnection,definecommandandrelatedparameters,performdifferenttypeofcommand,returndata,performoperationsonthedatabutdoesnotreturnanything,provideforward-onlyaccessandread-onlyaccessforreturningdataset.
IV.IIIPreparationofSpecializedDataAccessClass
Theabovetwomethodshavesomelimitations,agoodsolutionistoimproveitslevelofabstraction,thatis,bycreatingaspeciallyclasstoencapsulatetheusingofspecificdataprovider,andthroughdatastructurestoexchangeinformationwithotherlevelapplicationwhichhasnothingtodowithsuchas:specificdatasource,typeddataset",objectscollectionetc.
Wecancreateaspecialclassforeachsupportingdatasourcesinaparticularprogramset,andincaseofneed,loadthemfromtheapplicationaccordingtotheconfigurationfiles.So,ifwanttoaddnewdatasourcestoapplication,youwouldonly
needtoachieveanewclassaimatthedefinedrulesforagroupofgeneralinterface.
IfwantSQLServerasadatasourceandprovidesupport,youcoulddothefollowing
definition:
namespaceMYEXAMPIE{
publicclassSample:IDbSample{
publicDataTableGetSam(){
StringConnStr=
ConfigurationSettings.AppSettings[ConnStr"];
using(SqlConnectionconn=newSqlConnection(ConnStr)){
stringcmdString=SELECTID,nameFROMSample";
SqlCommandcmd=newSqlCommand(cmdString,conn);
SqlDataAdapterda=newSqlDataAdapter(cmd);
DataTabledt=newDataTable(Sample");
Da.Fill(dt);
returndt;}}
publicDataTableGetSamID(stringID){……}
publicboolInsertSam(){……}
……//Andotherachievedmethod
}}
SampleclassrealizeIDbSampleinterface.Wecanonlycreateanewclassthatrealizethisinterfacewhenneedtosupportnewdatasources.
Thistypeofinterfacecanbedefinedasfollowing:
namespaceCommon{
publicinterfaceIDbSample{
DataTableGetSam();
DataTableGetSamID(stringID);
boolInsertSam();}}
Othertypesofdatasourcesaresimilartotheabovecode,andhere,wewouldnotgiveunnecessarydetails.Theadvantageofthismethodis:ahighdegreeofdecoupling,easychanging,suitableforteamdevelopment.Thebenefitsofdecouplingareeasytotest.Whentest,wecansimulateadataaccesslayer,testbusinesslogicindependently,evencansimulatevariousdatabaseerrors,andalsocantestthedataaccesslayerseparately.
VSummary
Inwebsiteconstruction,therearesomeotherwaystovisitdatabasebyASP.NETbasedon.NETtechnology,andgenerally,itissimilar.Intheactualdevelopmentprocess,whichwaywouldbechosen?Weshouldnimblyselectaccordingtotheneeds.Inaddition,throughdatacontrolencapsulationfunctions,ASP.NETcouldbemoreflexibletocontroldata,andreducetherequiredcodewhenaccessanddisplaythedata.FromtraditionaldatabasetoXMLdatastorage,allkindsofdatasourcecanbeconnectedtothesecontrols,andalldatasourcescanbehandledinasimilarformat,greatlyreducesthedata-drivenapplicationdevelopmentcomplexity.Currently,ASP.NETisanidealchoiceforwebdatabasevisiting.
References
I..Sun,Z.-J.,Lu,L.:AnImplementofWebDatabaseAccessApplicationsBasedonMidwareTechnology.ComputerSystems&ApplicationsI.,VIIIVII–IX0(II00VIII)
II.Millett,S.:ProfessionalASP.NETDesignPatterns.Wrox(II0I.0)
III.Evjen,B.,Hanselman,S.,Rader,D.:ProfessionalASP.NETIII.VSPI.edn.InC#andVB.Wrox(II00IX)
IV.Zhou,S.-X.:ResearchonDataAccessTechnologyBasedonADO.NETII.0.ComputerTechnologyandDevelopmentI.VIII,I.IVIV–I.IVVI(II00VIII)
王进
GuilinUniversityofElectronicTechnologyTeachingPractice&ExperimentDepartment,China
桂林电子工业教学实践与实验系,中国
access_wj@I.VIIII.net
access_wj@I.VIIII.net
摘要:
本文介绍了ASP.NET的Web数据库访问的原理,阐述了III种连接方法和两种访问模型,对ASP.NET网页与数据库,然后分析和比较了使用ADO.NET的数据库访问技术的各种方法.同时,提供了I.些实用的代码.ASP.NET是目前I.个访问WEB数据库的理想选择.
关键字:ASP.NET;ADO.NET;Web数据库;数据访问
I..引言
数据访问是Web应用程序开发的关键问题.I.般企业应用程序需要数据驱动的Web页面,开发人员必须从不同的数据格式的数据源进行快速访问.当前的Windows环境下,有各种不同的Web数据库的访问技术.如:CGI(公共网关接口).ADC(先进数据库连接器).IDC(Internet数据库连接器).Java/JDBC.ASP和ASP.NET(ActiveServerPage)等.
ASP.NET是I.个由微软公司推出的由ASP发展而来的新I.代的Web应用程序开发技术,它为用户提供了I.个完整的视觉的开发环境.它紧密结合.NET框架并提供了I.种模块化的设计方法,多语言支持,代码与HTML设计是分开的.因此它的结构清晰.可读性高和执行效率高等优点.
ADO.NET是I.种微软.NET平台的不断更新和发展的数据库访问技术.它拥有I.个全新的设计理念,并在原有ADO基础上具有明显的创新.无论数据源是来自于何种数据库,它都 *好棒文|www.hbsrm.com +Q: 3_5_1_9_1_6_0_7_2
可以有效地进行访问.它是应用程序与数据库之间的重要桥梁.
在使用ADO.NET技术访问数据库的实现过程中,I.旦遇到对象模型或基本开发过程是自己不熟悉的,这通常导致技术故障.针对这I.事实,本文分析和探讨了在ASP.NET中如何访问数据库的技术.
II.访问原理
通过服务器端组件ADO.NET,ASP.NET实现Web数据库访问.ADO.NET为.Net框架提供优化的,面向网络的数据访问模型,它拥有它自己的XML格式和NET体系结构的ADO.NET接口.ADO.NET为应用程序提供了两种数据访问模式:连接模式和非连接模式.与传统的,非连接模式相比,增强了可靠性和稳定性.在这种模式中,I.旦应用程序从数据源中获得需要的数据,它会断开与原始数据源的连接,并以XML格式存储获得的数据.处理后,再和与原数据进行连接,并完成数据的更新.
ADO.NET包含两个核心组件:Dataset和NETFrameworkDataProvider.前者为非连接式结构的核心组件,实现了独立于任何数据源的数据访问和管理本地应用程序数据.后者是I.组包括Connection",Command",DataReader",DataAdapter"等有关对象的组件并提供了有关数据操作的方法,如数据的方法快速访问,只前进和只读访问.这其中,Connection"提供数据源的连接.Command"提供了获得数据.修改数据.运行存储过程和发送或检索参数信息的数据库命令.DataReader"提供了从数据源获得数据的高性能数据流,它是使用数据集连接数据源的桥梁.DataAdapter"使用Command"对象在数据源中执行SQL命令,它会载入数据到数据集中,使数据集的更新与数据源保持I.致.
III.连接方法
在I.个ASP.NET页面文件查询之前,插入.更新数据库,它应该首先与数据库建立I.个连接,然后做I.些相应的操作过程.
建立数据库连接的步骤是:
I..介绍相关的在页面文件的ADO.NET命名空间;
II.设置数据库连接参数;
III.根据连接参数,创建I.个数据库连接对象;
IV.执行数据库连接操作.
III.I..III种接线方式
ASP.NET通过ADO.NET访问数据库时有III种连接方式,第I.种,通过ADO.NET托管提供程序可以连接到任何ODBC;第II,通过ADO.NET托管提供程序可以连接到任何OLEDB数据中心;第III,通过SQL托管提供程序可以连接到MSSQLServer.I.般来说,在这III种方法中,SQL托管提供程序是效率最高的,其次是ADO.NET托管提供程序+OLEDB,最差的是ADO.NET托管提供程序+ODBC.
III.II.两种接入模式
ADO.NET根据不同形式的网站数据库提供了两种访问模式.I.个是流的从数据源读取的DataReader".另I.种是通过数据集来分离异构数据源.如果只想在网页上显示数据,很少需要操纵或改变它们,你可以通过使用ADO直接访问数据库.该模型利用SqlDataReader对象或OleDbDataReader对象来快速阅读.这些类等价于ADO快进指针(光标).他们与数据源保持I.个动态连接,但不能做任何改变.如果想从SqlDataReader或OleDbDataReader得到I.行数据, *好棒文|www.hbsrm.com +Q: 3_5_1_9_1_6_0_7_2
读"这个方法应该被采用.
如果想做I.个更复杂的交互访问,你应该通过ADO.NET使用DataSet对象.与传统的ADO技术相比,ADO.NET使用断开方法.那就是在ADO.NET中,无需使用游标与数据库建立I.个连接.相反,填充数据集(数据集)到从数据库中提取副本的信息中.如果数据集信息已经改变,在数据库中相应的信息不可改变.那就是,你可以很容易的改变而不用担心操纵数据,因为数据库连接是I.个不重要的.如果有必要,数据集可以被连接到原始数据源并应用于所有更改.
数据库访问的示意图:图I.
IV.ASP.NET数据库访问
通用数据库访问的方式主要有以下几种:
IV.I..使用通用数据访问方法
这是ADO.NET的标准程序.方法:通过采用简单对象模型,如连接",命令"和数据集"等,编写出可以连接到各种不同数据源的应用.IV.I.UsingCommonDataAccessMethods
示例代码如下:
OleDbConnectionConn=new
OleDbConnection(Provider=Microsoft.Jet.OLEDB.IV.0,"+
DataSource="+Server.MapPath(example.mdb"));
//connectionobject
Conn.Open();//openconnectionobject
OleDbCommandComm=newOleDbCommand(select*from
sample",Conn);
//querydatafromsample
OleDbDataReaderdr=Comm.ExecuteReader();
//Datareadobject
……
OleDbDataAdapterda=newOleDbDataAdapter(select*from
sample",Conn);
DataSetds=newDataSet();
Da.Fill(ds,sample");
dgid.DataSource=ds.Tables[sample"].DefaultView;
//
dgid.DataBind();
但事实上,可编程性和不同数据源的特点是V花VIII门,上面的方法使用了所有的数据源提供的共识"功能,.所以在这种方法中,数据源特定选项的优势将会丧失,不能提供访问和操纵各种数据库信息的最佳方法.
IV.II.使用基本的界面
通过接口(IDbConnection.IDbCommand.IDataReader等),代码将被封装在I.个具体到I.个特定的数据源的类中,所以独立于后端数据库服务器的剩下应用程序将受它的影响.通常情况下,接口的主要工作是:定义字符串的连接,打开和关闭连接,定义命令及相关参数,执行不同类型的命令,返回数据,对数据执行操作但不返回任何值.提供单向访问和对返回的数据集进行只读访问.
IV.III.专业数据访问类的准备
上述两种方法有I.定的局限性,I.个好的改善抽象水平的解决方案是,通过创建I.个特殊类来封装特定数据供应者的使用,并通过数据结构和与其他应用程序无关的层次来交换信息,如:特定的数据源,数据集的类型化,对象集合等.我们可以为每个支持在I.个特定程序集的数据源创建I.个特殊的类,并在需要的情况下,根据配置文件从应用程序加载它们.所以,如果想添加新数据源到应用程序中,你只需要在定义好的I.组通用接口规则中实现I.个新类目标.如果希望SQLServer作为数据源并提供支持,你可以做以下定义:
namespaceMYEXAMPIE{
publicclassSample:IDbSample{
publicDataTableGetSam(){
StringConnStr=
ConfigurationSettings.AppSettings[ConnStr"];
using(SqlConnectionconn=newSqlConnection(ConnStr)){
stringcmdString=SELECTID,nameFROMSample";
SqlCommandcmd=newSqlCommand(cmdString,conn);
SqlDataAdapterda=newSqlDataAdapter(cmd);
DataTabledt=newDataTable(Sample");
Da.Fill(dt);
returndt;}}
publicDataTableGetSamID(stringID){……}
publicboolInsertSam(){……}
……//Andotherachievedmethod
}}
实现IDbSample接口的类示例.我们只能创建I.个新类,当需要支持新的数据源时来实现这个接口.这种接口可以定义如下:
namespaceCommon{
publicinterfaceIDbSample{
DataTableGetSam();
DataTableGetSamID(stringID);
boolInsertSam();}}
其他类型的数据源类似于上面的代码,在这里,我们不会给不必要的细节.这种方法的优点是:高度的解耦,容易改变,适合团队开发.解耦的好处是容易测试.当测试时,我们可以模拟I.个数据访问层,独立测试业务逻辑,甚至可以模拟各种数据库错误,也可以单独测试数据访问层.
V.小结
在网站建设中,有I.些.NET的ASP.NET技术访问数据库的其他方法,通常,它是类似的.在实际的开发过程中,哪种方式会被选择?我们应该根据需要灵活选择.此外,通过数据控制封装功能,当访问和显示数据时,ASP.NET可以更灵活的控制数据,并减少所需的代码.从传统数据库到XML数据存储,各种数据源可以被连接到这些控制,并且所有的数据源可以以类似的格式来处理,大大减小了数据驱动应用程序开发的复杂性.目前,ASP.NET是I.个用于Web数据库访问的理想选择.
参考文献
I..Sun,Z.-J.,Lu,L.:AnImplementofWebDatabaseAccessApplicationsBasedonMidware
Technology.ComputerSystems&ApplicationsI.,VIIIVII–IX0(II00VIII)
II.Millett,S.:ProfessionalASP.NETDesignPatterns.Wrox(II0I.0)
III.Evjen,B.,Hanselman,S.,Rader,D.:ProfessionalASP.NETIII.VSPI.edn.InC#andVB.
Wrox(II00IX)
IV.Zhou,S.-X.:ResearchonDataAccessTechnologyBasedonADO.NETII.0.Computer
TechnologyandDevelopmentI.VIII,I.IVIV–I.IVVI(II00VIII)
附件II:外文原文(复印件)
WebDatabaseAccessTechnologyBasedonASP.NET
JinWang
GuilinUniversityofElectronicTechnologyTeachingPractice&ExperimentDepartment,China
access_wj@I.VIIII.net
Abstract:
ThisarticlepresentstheprincipleaboutWebdatabaseaccessbasedon
ASP.NET,expoundsthreekindsofconnectionmethodsandtwoaccessing
modelsthataboutASP.NETpageanddatabase,andthenanalyzesandcompares
variousmeansaboutusingADO.NETtechnologyondatabaseaccess.Inthe
meantime,providessomeutilitycodes.ASP.NETiscurrentlyanidealchoiceforvisitingWebdatabase.
Keywords:ASP.NET,Webdatabase,ADO.NET,dataaccess.
I.Introduction
Dataaccessisakeyissueonwebapplicationdevelopment.Generalbusinessapplicationneedsdata-drivenWebpages,developermustquicklyaccessthedatafromdifferentformatsdatasource.Underthecurrentwindowsenvironments,therearevarioustechnologiesonwebdatabaseaccess.Suchas:CGI(CommonGatewayInterface).ADC(AdvanceDatabaseConnector).IDC(InternetDatabaseConnector).Java/JDBC.ASPandASP.NET(ActiveServerPage)etc.
ASP.NETisanewgenerationtechnologyofwebapplicationdevelopmentthattheMicrosoftCompanylaunchesfollowingtheASP,andprovidesacompletevisual
developmentenvironmentforusers.Itcloselyintegrateswiththe.NETFrameworkandprovidesamodulardesignmethod,supportsformultipleprogramminglanguages,codeandHTMLdesignisseparated.Itismoreclearlystructure,morereadableandhighefficiency.
ADO.NETisanuptodatedatabaseaccesstechnologyattheMicrosoft.NET
platform.Ithasabrandnewdesignconcept,andhasasignificantinnovationsbasedontheoriginalADO.Nomatterwhichdatabasethedatasourcescomefrom,allofthemcanbeeffectivelyaccessed.Itisanimportantbridgebetweenapplicationsanddatabases.
DuringtheimplementationprocessofusingADO.NETtechnologytovisitdatabase,onaccountofunfamiliarwithobjectmodelandbasicdevelopmentoperation,usuallyleadtotechnicalfault.Inresponsetothisfact,thisarticleanalysesanddiscussesthetechnologyofdatabaseaccessinASP.NET.
IIAccessPrinciple
ThroughServer-sidecomponentADO.NET,ASP.NETrealizeswebdatabasevisiting.ADO.NETprovidesoptimized,facingwebdataaccessmodelforthe.NETframework,ithasitsownADO.NETinterfacebasedonXMLformatand.NETarchitecture.ADO.NETprovidestwodataaccessmodelsfortheapplication:connectionmodeandnon-connectionmode.Comparedwiththetraditional,non-connectionmodestrengthensthereliabilityandstability.Inthismode,oncetheapplicationobtainstherequireddatafromthedatasource,itwoulddisconnecttheconnectionwiththeoriginaldatasource,andstoretheobtainingdataintheformofXML.Afterhandling,itthenmadetheconnectionwiththeoriginaldataandcompletesthedataupdating.
ADO.NETincludestwocorecomponents:Datasetand.NETFrameworkdataprovider.Theformerisacorecomponentofoff-typestructure,whichrealizesdataaccessindependentlyofanydatasourceandmanageslocalapplicationdata.ThelatterisagroupcomponentincludingobjectsaboutConnection",Command",DataReader",DataAdapter",andprovidesmethodsaboutdatamanipulation,datafastaccess,forward-onlyandread-onlyaccess.Amongthis,Connection"providesconnectivitywiththedatasources.Command"providesdatabasecommandsusedforreturningdata,modifyingdata,runningstoredproceduresandsendingorretrievingparameterinformation.DataReader"provideshigh-performancedataflowfromdatasourceanditisabridgethatconnectsthedatasourcewithDataset.DataAdapter"usesCommand"objectstoexecuteSQLcommandinthedatasource,anditwouldloadthedataintotheDataset,makethechangestotheDatasetconsistentwiththedatasource.
IIICnnectionMethod
BeforeanASP.NETpagefilequery,insert,updatethedatabase,itshouldestablisha
connectionwiththedatabasefirst,andthendosomecorrespondingoperationprocess.
Thestepstoestablishdatabaseconnectionis:
I..IntroduceassociatedADO.NETnamespaceinthepagefile
II.Setdatabaseconnectionparameters
III.Accordingtotheconnectionparameters,createadatabaseconnectionobject
IV.Executedatabaseconnectionoperation
III.I.ThreeKindsofConnectionMode
TherearethreeconnectionwaysthatASP.NETvisitsdatabasethroughADO.NET,thefirstone,throughADO.NETManagedProvidercouldconnecttoanyODBC;thesecond,throughADO.NETManagedProvidercouldconnecttoanyOLEDBdatacenter;thethirdwaythroughSQLManagedProvidercouldconnecttoMSSQLServer.Generally,inthesethreemethods,SQLManagedProviderismostefficient,followedbyistheADO.NETManagedProvider+OLEDB,theworstoneisADO.NETManagedProvider+ODBC.
III.IITwoAccessModel
ADO.NETprovidestwoaccessingmodelsaccordingtodifferentformsofWebdatabase.OneisDataReader"thatreadfromdatasourcebasedonstream.AnotheristhroughtheDatasettoisolateheterogeneousdatasource.Ifonlywanttodisplaydataonawebpageandseldomneedtomanipulateorchangethem,youcandirectlyaccessthedatabasebyusingADO.NET.ThismodelutilizesSqlDataReaderobjectorOleDbDataReaderobjectforfastreading.TheseclassesareequivalenttoADOfastforwardpointer(cursor).Theykeepanactivityconnectionwithdatasource,butcannotmakeanychanges.IfwanttogetarowofdatafromsqIDataReaderorOleDbDataReader,theRead"methodshouldbeused.
Ifwanttodoamorecomplexinteractiveaccess,youshoulduseDataSetobjectthroughADO.NET.ComparedwiththetraditionalADOtechnology,ADO.NETusesdisconnectmethod.Thatis,intheADO.NET,createaconnectiontothedatabase
withoutusingcursors.Instead,filldataset(DataSet)withinformationcopiesextractedfromadatabase.Ifthedatasetinformationhasbeenchanged,thecorrespondinginformationindatabasewouldnotbechanged.Thatis,youcaneasilychangeandmanipulatedatawithoutworry,becausethedatabaseconnectionisnottheimportantone.Ifnecessary,theDatasetcanbeconnectedbacktotheoriginaldatasourcesandapplyallchanges.
Schematicdiagramofdatabaseaccess:Fig.I.
Fig.I..
IVASP.NETDatabaseAccess
Commondatabaseaccesswaybasicallyhasthefollowingkinds:
IV.I.UsingCommonDataAccessMethods
ThisisthestandardprocedureforADO.NET.Themethodis:byusingsimpleobject
model,suchasConnection",Command"andRecordset"etc,writeoutapplicationsthatcouldconnecttoallkindsofdifferentdatasources.
Samplecodeisasfollows:
OleDbConnectionConn=new
OleDbConnection(Provider=Microsoft.Jet.OLEDB.IV.0,"+
DataSource="+Server.MapPath(example.mdb"));
//connectionobject
Conn.Open();//openconnectionobject
OleDbCommandComm=newOleDbCommand(select*from
sample",Conn);
//querydatafromsample
OleDbDataReaderdr=Comm.ExecuteReader();
//Datareadobject
……
OleDbDataAdapterda=newOleDbDataAdapter(select*from
sample",Conn);
DataSetds=newDataSet();
Da.Fill(ds,sample");
dgid.DataSource=ds.Tables[sample"].DefaultView;
//
dgid.DataBind();
Butinfact,theprogrammabilityandfeaturesofvarietydatasourcesaremultifarious,andtheabovemethoduseCommonground"offunctionthatallthedatasourcehaveprovided.Sointhisapproach,theadvantageofdatasourcespecificoptionwillbelost,andcouldnotprovidethebestmethodofaccessingandmanipulatinginformationinvariousRDBMS.
IV.IIUsingBasicInterface
Throughinterface(IDbConnection.IDbCommand.IDataReaderetc),thecodewillbeencapsulatedinaclassspecifictoaparticulardatasource,sotherestoftheapplicationindependentoftheback-enddatabaseserverandwouldfromitseffects.Usually,themainworkofinterfaceis:defineconnectionstring,openandclosetheconnection,definecommandandrelatedparameters,performdifferenttypeofcommand,returndata,performoperationsonthedatabutdoesnotreturnanything,provideforward-onlyaccessandread-onlyaccessforreturningdataset.
IV.IIIPreparationofSpecializedDataAccessClass
Theabovetwomethodshavesomelimitations,agoodsolutionistoimproveitslevelofabstraction,thatis,bycreatingaspeciallyclasstoencapsulatetheusingofspecificdataprovider,andthroughdatastructurestoexchangeinformationwithotherlevelapplicationwhichhasnothingtodowithsuchas:specificdatasource,typeddataset",objectscollectionetc.
Wecancreateaspecialclassforeachsupportingdatasourcesinaparticularprogramset,andincaseofneed,loadthemfromtheapplicationaccordingtotheconfigurationfiles.So,ifwanttoaddnewdatasourcestoapplication,youwouldonly
needtoachieveanewclassaimatthedefinedrulesforagroupofgeneralinterface.
IfwantSQLServerasadatasourceandprovidesupport,youcoulddothefollowing
definition:
namespaceMYEXAMPIE{
publicclassSample:IDbSample{
publicDataTableGetSam(){
StringConnStr=
ConfigurationSettings.AppSettings[ConnStr"];
using(SqlConnectionconn=newSqlConnection(ConnStr)){
stringcmdString=SELECTID,nameFROMSample";
SqlCommandcmd=newSqlCommand(cmdString,conn);
SqlDataAdapterda=newSqlDataAdapter(cmd);
DataTabledt=newDataTable(Sample");
Da.Fill(dt);
returndt;}}
publicDataTableGetSamID(stringID){……}
publicboolInsertSam(){……}
……//Andotherachievedmethod
}}
SampleclassrealizeIDbSampleinterface.Wecanonlycreateanewclassthatrealizethisinterfacewhenneedtosupportnewdatasources.
Thistypeofinterfacecanbedefinedasfollowing:
namespaceCommon{
publicinterfaceIDbSample{
DataTableGetSam();
DataTableGetSamID(stringID);
boolInsertSam();}}
Othertypesofdatasourcesaresimilartotheabovecode,andhere,wewouldnotgiveunnecessarydetails.Theadvantageofthismethodis:ahighdegreeofdecoupling,easychanging,suitableforteamdevelopment.Thebenefitsofdecouplingareeasytotest.Whentest,wecansimulateadataaccesslayer,testbusinesslogicindependently,evencansimulatevariousdatabaseerrors,andalsocantestthedataaccesslayerseparately.
VSummary
Inwebsiteconstruction,therearesomeotherwaystovisitdatabasebyASP.NETbasedon.NETtechnology,andgenerally,itissimilar.Intheactualdevelopmentprocess,whichwaywouldbechosen?Weshouldnimblyselectaccordingtotheneeds.Inaddition,throughdatacontrolencapsulationfunctions,ASP.NETcouldbemoreflexibletocontroldata,andreducetherequiredcodewhenaccessanddisplaythedata.FromtraditionaldatabasetoXMLdatastorage,allkindsofdatasourcecanbeconnectedtothesecontrols,andalldatasourcescanbehandledinasimilarformat,greatlyreducesthedata-drivenapplicationdevelopmentcomplexity.Currently,ASP.NETisanidealchoiceforwebdatabasevisiting.
References
I..Sun,Z.-J.,Lu,L.:AnImplementofWebDatabaseAccessApplicationsBasedonMidwareTechnology.ComputerSystems&ApplicationsI.,VIIIVII–IX0(II00VIII)
II.Millett,S.:ProfessionalASP.NETDesignPatterns.Wrox(II0I.0)
III.Evjen,B.,Hanselman,S.,Rader,D.:ProfessionalASP.NETIII.VSPI.edn.InC#andVB.Wrox(II00IX)
IV.Zhou,S.-X.:ResearchonDataAccessTechnologyBasedonADO.NETII.0.ComputerTechnologyandDevelopmentI.VIII,I.IVIV–I.IVVI(II00VIII)
版权保护: 本文由 hbsrm.com编辑,转载请保留链接: www.hbsrm.com/lwqt/wxzs/76.html