从DAO转换到ADO

2016-02-19 12:53 25 1 收藏

下面,图老师小编带您去了解一下从DAO转换到ADO,生活就是不断的发现新事物,get新技能~

【 tulaoshi.com - 编程语言 】

SwitchfromDAOtoADO
  
  BySamHuggill
  
  Introduction
  
  Afewdaysago,IstartedanewprojectthathandlesalargedatabasecontainingHTMLcodeforacompletewebsite.Theprojecthastoallowthewebmastersofthewebsiteviewallupdatesmadetothesite,whentheyweremadeandbywhom.Theycanalsoeditthepagesonthesite,andautomaticallyuploadthem.
  
  ThisprojectrequirestheuseofafairlylargedatabasethatneedstobeaccessedbymanypeoplefromdifferentPCs.IdecidedtouseSQLServerasthebackendtotheproject,butthismeantthatIcouldn注释:tuseDAOtoconnecttoit!Whatapain!
  
  So,IdecideditwasabouttimeIstartedtolearnADO.ItookaquickglancearoundonthenetatmyusualVBsites,butfoundlittleornohelpformeonADO.
  
  Well,asweprideourselveshereatVBSquareonaddingoriginalcontent,IdecidedIwouldwriteanarticleonusingADO.
  
  ThisarticleisonlyreallytogetyoustartedonADO,andonlydiscussestheconnectionandrecordsetobjects.TherearemanymorefeaturesofADOthatyouwillneedtolookintobeforeyoutakeonaprojectusingADO.
  Connectingtolocalandexternaldatabases
  
  WithADO,youcanbuildallyourcodearoundalocaldatabaseandthen,veryeasilychangeonelineofcodethatwillallowyoutoaccessadatabaseonaSQLServer.
  
  Thethingthattookmeawhiletofigureout,washowtoconnecttoadatabase.WithDAO,youusetheOpenDatabasecommandpassingthepathofthedatabaseasoneofthearguements.ButwithADO,youneedtobuildaconnectionstring.Toconnecttoalocaldatabase,usethefollowingconnectionstring:
  
  ConnectionString="Provider=Microsoft.JET.OLEDB.3.51;DataSource=c:mydb.mdb"
  
  Thatmayseemabitcumbersome,butthisflexibilityprovidesyouwiththemeanstoconnecttoalmostanydatabaseinanyformatanywhere.ThefollowingconnectionstringisusedtoconnecttoaSQLSeverdatabasenamed注释:people注释::
  
  ConnectionString="driver=[SQLServer];uid=admin;server=myserver;database=people"
  SwitchfromDAOtoADO
  
  BySamHuggill
  
  UsingtheConnectionObject
  
  TheConnectionobjectisthebasefromwhichalmostallADOfunctionsderivefrom.Youcanusethisobjecttocarryoutmostoftheactionsperformedinthesamplecode,usingSQLstatements.E.g.
  
  mCN.Execute"DELETEFROMPeopleWHEREID=1"
  
  Iwon注释:tgointoanydetailaboutusingSQLstatements,buttheMSDNhassomeinfoonthem.
  
  TheconnectionobjectreturnsarecordsetobjectifyouusetheExecutemehtod.YoucanusethistocreateaDLLanduseCOMtogetthecontentsofarecordset.e.g.
  
  PublicSubGetRecordSet()AsADODB.Recordset
  GetRecordSet=mCN.Execute("SELECT*FROMPeople")
  EndSub
  
  Thismeansthatyoucancentralizeallyoudatabasecodeintoonecomponent,preferablyaDLL.
  
  UsingtheRecordsetObject
  
  InADO,theRecordsetobjectisverysimilartotheDAORecordsetobject.Thismakesthingsaloteasierwhenportingyourcode,althoughyouwillneedtodeviseafewworkaroundstoovercomeafewmissingfeatures.
  
  Forexample,whenyouinsertarecord,butneedtostoreitsID(AutoNumber)valueinthesameaction,youwouldnormallyusethiscodeinDAO:
  
  Withrs
  .AddNew
  .Fields("Name").value=sNewValue
  .Update
  .Bookmark=.Lastmodified
  m_intRcdID=.Fields("ID").value
  .Close
  EndWith
  TheADORecordsetobjectdoesnotexposeaLastModifiedorLastUpdatedproperty,soweneedtousethefollowingworkaround:
  
  Withrs
  .AddNew
  .Fields("Name").value=sNewValue
  .Update
  .Requery
  .MoveLast
  m_intRcdID=.Fields("ID").value
  .Close
  EndWith
  
  Afterupdatingtherecordset(whichyoudon注释:tneedtodoifyouaremovingtoanotherrecord,asADOautomaticallyupdateschangesmadewhenyoumoverecords)youneedtorefreshtherecordsetusingtheRequerymethod.Thenyouneedtomovetothelastrecord,whichistheoneyouhavejustadded.Now,justextracttheIDvalueandstoreitinamembervariable.
  SampleApplication
  
  TohelpyoumovefromDAOtoADO,IhavemadeasimilarsampleapplicationasIdidfortheBeginningDatabasesarticle.Thesampleoffersthesefeatures:
  
  Addingnewrecords
  Deletingrecords
  Updatingrecords
  Gettingrecorddata
  Itisaverysimpledemo,butshouldhelpyoutounderstandthebasics.ItusethelatestversionofADO,version2.1.SeethesectionatthebottomfordownloadingtheADOLibrariesandthesampleapplcation.
  
  Togetthesampleapplicationtowork,startanewStandardEXEProjectandaddareferencetotheMicrosoftActiveXDataObjects2.1Library(Project,References).Addfourcommandbuttons(cmdAdd,cmdDelete,cmdGet,cmdSave)andthreetextboxes(txtNotes,txtURL,txtName).Copy/pastethefollowingcodeintotheform:
  
  OptionExplicit
  
  注释:PrivatereferencestotheADO2.1ObjectLibrary
  PrivatemCNAsConnection
  PrivatemRSAsNewRecordset
  
  注释:InternalreferencetothecurrentrecordsIDvalue
  PrivatemintRcdIDAsInteger
  
  PrivateSubcmdAbout_Click()
  frmAbout.ShowvbModal
  EndSub
  
  PrivateSubcmdAdd_Click()
  AddRecord
  EndSub
  
  PrivateSubcmdClose_Click()
  UnloadMe
  EndSub
  
  PrivateSubOpenConnection(strPathAsString)
  
  注释:Closeanopenconnection
  IfNot(mCNIsNothing)Then
  mCN.Close
  SetmCN=Nothing
  EndIf
  
  
  注释:Createanewconnection
  SetmCN=NewConnection
  
  WithmCN
  注释:ToconnecttoaSQLServer,usethefollowingline:
  
  注释:.ConnectionString="driver=[SQLServer];uid=admin;server=mysrv;database=site"
  
  注释:Forthisexample,wewillbeconnectingtoalocaldatabase
  .ConnectionString="Provider=Microsoft.JET.OLEDB.3.51;DataSource="&strPath
  
  .CursorLocation=adUseClient
  .Open
  
  EndWith
  
  EndSub
  
  PrivateSubAddRecord()
  
  
  注释:Addanewrecordusingtherecordsetobject
  注释:Couldbedoneusingtheconnectionobject
  mRS.Open"SELECT*FROMPeople",mCN,adOpenKeyset,adLockOptimistic
  
  WithmRS
  
  .AddNew
  .Fields("Name").Value=txtName.Text
  .Fields("URL").Value=txtURL.Text
  .Fields("Notes").Value=txtNotes.Text
  
  注释:Afterupdatingtherecordset,weneedtorefreshit,andthenmovetothe
  注释:endtogetthenewestrecord.Wecanthenretrievethenewrecord注释:sid
  .Update
  .Requery
  .MoveLast
  
  mintRcdID=.Fields("ID").Value
  
  .Close
  
  EndWith
  
  EndSub
  
  PrivateSubDeleteRecord()
  
  注释:Deletearecordandclearthetextboxes
  
  mRS.Open"SELECT*FROMPeopleWHEREID="&mintRcdID,mCN,adOpenKeyset,adLockOptimistic
  
  mRS.Delete
  mRS.Close
  
  txtName.Text=""
  txtURL.Text=""
  txtNotes.Text=""
  
  EndSub
  
  PrivateSubGetInfo()
  
  注释:GetthedataforarecordbasedonitsIDvalue
  mRS.Open"SELECT*FROMPeopleWHEREID="&
  mintRcdID,mCN,adOpenKeyset,adLockOptimistic
  
  WithmRS
  
  txtName.Text=.Fields("Name").Value
  txtURL.Text=.Fields("URL").Value
  txtNotes.Text=.Fields("Notes").Value
  .Close
  
  EndWith
  
  EndSub
  
  PrivateSubUpdateRecord()
  
  注释:Updatearecord注释:svalues
  mRS.Open"SELECT*FROMPeopleWHEREID="&mintRcdID,mCN,adOpenKeyset,adLockOptimistic
  
  WithmRS
  
  .Fields("Name").Value=txtName.Text
  .Fields("URL").Value=txtURL.Text
  .Fields("Notes").Value=txtNotes.Text
  
  .Update
  .Close
  
  EndWith
  
  EndSub
  
  PrivateSubcmdDelete_Click()
  DeleteRecord
  EndSub
  
  PrivateSubcmdGet_Click()
  
  注释:Asktheuserwhichrecordshouldberetrievedandgetthedata
  注释:forthatrecord
  mintRcdID=Val(InputBox$("EnterIDofrecord:",App.Title,"1"))
  
  GetInfo
  
  EndSub
  
  PrivateSubcmdSave_Click()
  UpdateRecord
  EndSub
  
  PrivateSubForm_Load()
  
  OpenConnectionApp.Path&"people.mdb"
  
  EndSub
  
  PrivateSubForm_Unload(CancelAsInteger)
  
  IfNot(mRSIsNothing)Then
  SetmRS=Nothing
  EndIf
  
  IfNot(mCNIsNothing)Then
  mCN.Close
  SetmCN=Nothing
  EndIf
  
  EndSub->

来源:https://www.tulaoshi.com/n/20160219/1602292.html

延伸阅读
各种文件转换到PDF文件格式的方法及优缺点介绍    PDF文件,这是一种应用广泛的文件类型,比如企业之间传递电子文档料等。正是由于这种文件类型应用的广泛性,才有了将各种文件转换为pdf格式的需求。下面一起看看将文件转换为pdf格式的方法和优缺点。 现在多数办公软件,都可以将自身的文件类型转换成PDF文件。比...
=============Student.Java========== import java.sql.*; public class Student implements java.io.Serializable{ private String id; private String name; private Date birthday; public Student(){} public Student(String id, String name, Date birthday){ this.id = id; this...
ADO 与ADO.NET摘要ADO与ADO.NET是微软提供的一种高性能访问信息源的策略,这些技术可以使企业很方便的整合多种数据源,创建易维护的解决方案。目录1. ADO与ADO.NET简介2. 数据访问方式的历史3. ADO与ADO.NET对照4. 小结 1. ADO与ADO.NET简介ADO与ADO.NET既有相似也有区别,他们都能够编写对数据库服务器中的数据进行访问和操作的应用程序,并且...
您可以通过将 ADO.NET 的各项功能与 ActiveX 数据对象 (ADO) 的特定功能进行比较来理解 ADO.NET 的功能。数据的内存中表示形式 在 ADO 中,数据的内存中表示形式为记录集。在 ADO.NET 中,它为数据集。它们之间有重要的差异。表的个数 记录集看起来像单个表。如果记录集将包含来自多个数据库表的数据,则它必须使用 JOIN 查询,将来自各个数据...
简介 ActiveXDataObjects(ADO)是微软最新的数据访问技术。它被设计用来同新的数据访问层OLEDBProvider一起协同工作,以提供通用数据访问(UniversalDataAccess)。OLEDB是一个低层的数据访问接口,用它可以访问各种数据源,包括传统的关系型数据库,以及电子邮件系统及自定义的商业对象。 ADO向我们提供了一个熟悉的,高层的对OLEDB的Au...

经验教程

435

收藏

88
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部