当前位置:主页>Visual Basic教程>文章内容
从DAO转换到ADO
来源: 作者: 发布时间:2007-04-29  
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->


 
上一篇:VB5.0数据库编程经验小集   下一篇:Access97的报表解决方案
 
  相关文章
·VB5.0数据库编程经验小集
·Access97的报表解决方案
·用数据库保存VB程序的用户设置
·ADO简介
·Text转换为AccessMDB
·在VB中存取数据库中的图片
·在VB中运行MicrosoftAccess报表的好方
·ADO控件和DATA控件的冲突(不能共存)
·在VB6.0中实现动态统计报表
·用VB建立Access数据库结构
·开发ADOCE搭配WinCE资料存取应用程序(2
·功能强大的SendMessage函数
 
【关闭窗口】
推荐本站资源
最新文章