网络编程 | 站长之家 | 网页制作 | 图形图象 | 操作系统 | 冲浪宝典 | 软件教学 | 网络办公 | 邮件系统 | 网络安全 | 认证考试 | 系统进程
Firefox | IE | Maxthon | 迅雷 | 电驴 | BitComet | FlashGet | QQ | QQ空间 | Vista | 输入法 | Ghost | Word | Excel | wps | Powerpoint
asp | .net | php | jsp | Sql | c# | Ajax | xml | Dreamweaver | FrontPages | Javascript | css | photoshop | fireworks | Flash | Cad | Discuz!
当前位置 > 网站建设学院 > 网络编程 > Visual Basic
Tag:注入,存储过程,分页,安全,优化,xmlhttp,fso,jmail,application,session,防盗链,stream,无组件,组件,md5,乱码,缓存,加密,验证码,算法,cookies,ubb,正则表达式,水印,索引,日志,压缩,base64,url重写,上传,控件,Web.config,JDBC,函数,内存,PDF,迁移,结构,破解,编译,配置,进程,分词,IIS,Apache,Tomcat,phpmyadmin,Gzip,触发器,socket
网络编程:ASP教程,ASP.NET教程,PHP教程,JSP教程,C#教程,数据库,XML教程,Ajax,Java,Perl,Shell,VB教程,Delphi,C/C++教程,软件工程,J2EE/J2ME,移动开发
本月文章推荐
.VB编程的几个API函数的应用问题.
.利用VB设计打印复杂报表.
.HierarchicalFlexGrid控件的使用.
.递归过程在VB中的应用实例.
.VB开发通讯软件.
.为常量定义合适的类型.
.用VB实现浮动按钮.
.用WinSock设计Chat程序.
.VB6实现局域网多站点互连手册.
.菜单项的动态装入.
.如何用VB在桌面建立快捷方式.
.静态变量慢于动态变量.
.ADO简介.
.在VB中实现移动没有标题栏的窗口.
.利用VB三维面板控件设计流动条.
.给应用程序添加“日积月累”对话.
.VBCOM基础讲座之创建第一个COM对.
.VB开发技巧三则.
.利用PictureClip进行图像局部处理.
.VB6.0初学者的10个编程小技巧.

从DAO转换到ADO

发表日期:2006-2-27


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数据库编程经验小集 人气:3130
下一篇:Access97的报表解决方案 人气:3658
浏览全部Visual Basic的内容 Dreamweaver插件下载 网页广告代码 祝你圣诞节快乐 2009年新年快乐