You are on page 1of 10

Chng Mi Lm - Lp trnh vi k thut DAO

Reference DAO
Trong bi ny ta s hc nhng cch lp trnh cn bn vi MS Access database qua k thut DAO m khng cn dng n Control Data nh trong bi trc. Ta s cn n vi Objects trong th vin DAO, do nu bn m mt d n VB6 mi th hy dng Menu Command Project | References... chn Microsoft DAO 3.51 Object Library bng cch click ci checkbox bn tri nh trong hnh di y. (Mt cch nh tn ca Object ny l nh cu "thng cha cua O 35 con d").

Sau trong code ca Form chnh ta s declare variable myDatabase cho mt instance ca DAO database v variable myRS cho mt DAO recordset. y ta ni r Database v Recordset l thuc loi DAO phn bit vi Database v Recordset thuc loi ADO (ActiveX Data Object) sau ny. l Intellisense gip ta trong lc vit code:

By gi bn hy t ln Form chnh, tn frmDAO, 4 labels vi captions: Title, Year Published, ISBN v Publisher ID. K cho thm 4 textboxes tng ng v t tn

chng l txtTitle, txtYearPublished, txtISBN v txtPublisherID. iu ta mun lm l khi Form mi c loaded, n s ly v t database mt Recordset cha tt c records trong table Titles theo th t v mu t (alphabetical order) ca field Title v hin th record u tin.

Dng keyword SET


Chuyn trc ht l m mt Database Object da vo tn y (full path name) ca Access database:
' Open main database Set myDB = OpenDatabase(AppFolder & "BIBLIO.MDB")

ch Set trong cu code trn. l v myDB l mt Pointer n mt Object. Mc du t ry v sau ta s dng myDB nh mt Database theo cch ging nh bt c variable thuc data type no khc, nhng khi ch nh ln u l n t u n th ta dng ch Set, ni rng tht ra myDB khng phi l Object Database, nhng l Pointer n Object Database. im ny cng ni n cng kh hiu. i khi l VB6 runtime dynamically allocates (dnh ra cho khi cn) mt phn trong b nh (memory) cha Object Database khi ta nhn c n t execution ca Method OpenDatabase. Du v tr ch cha Object Database trong b nh khng nht nh, nhng v ta nm ci cn ch n v tr y nn ta vn c th lm vic vi n mt cch bnh thng. Ci cn y l value (tr s) ca variable myDB. V value ny khng phi l Object, nhng n cha memory address ch n (point to hay refer to) Object Database, nn ta gi n l Pointer. Lp trnh dng Pointer ni chung rt linh ng l hiu nng trong cc ngn ng nh C, Pascal, C++ ,v.v.. Tuy nhin, lp trnh vin phi nh tr li Operating System phn memory mnh dng khi khng cn cn n na Operating System li allocate cho Object khc. Nu cng vic qun l dng li memory khng n tha th c nhng mnh memory nm lang bang m Operating Sytem khng bit. Ln ln Operating System s khng cn memory d na. Ta gi hin tng y l memory leakage (r). Cc ngn ng sau ny nh Java, C# u khng dng Pointer na. Visual Basic khng mun lp trnh vin dng Pointer. Ch trong vi trng hp c bit VB6 mi l ra cho ta thy tht ra trong hu trng VB6 Runtime dng Pointer, nh trong trng hp ny. Tng t nh vy, v Recordset l mt Pointer n mt Object, ta cng dng Set khi ch nh mt DAO Recordset ly v t Method OpenRecordset ca database myDB.
'Open recordset Set myRS = myDB.OpenRecordset("Select * from Titles ORDER BY Title")

Ci parameter loi String ta dng cho method OpenRecordset l mt Lnh (Statement) SQL. N ch nh cho database ly tt c mi fields (columns) (Select *) ca mi record t Table Titles (from Titles) lm mt Recordset v sort cc records trong Recordset y theo alphabetical order ca field Title (ORDER BY Title). Nh l Recordset ny cng ging nh property Recordset ca mt Control Data m ta dng trong bi trc. By gi c Recordset ri, ta c th hin th chi tit ca record u tin nu Recordset y c t nht mt record. Ta kim tra iu y da vo property RecordCount ca Recordset nh trong code di y:
Private Sub Form_Load()

' Fetch Folder where this program EXE resides AppFolder = App.Path ' make sure it ends with a back slash If Right(AppFolder, 1) <> "\" Then AppFolder = AppFolder & "\" ' Open main database Set myDB = OpenDatabase(AppFolder & "BIBLIO.MDB") 'Open recordset Set myRS = myDB.OpenRecordset("Select * from Titles ORDER BY Title") ' if Recordset is not empty then display the first record If myRS.RecordCount > 0 Then myRS.MoveFirst ' move to first record Displayrecord ' display details of current record End If End Sub

Sau khi dng method MoveFirst ca Recordset position current record Record u tin, ta hin th tr s cc fields ca record bng cch assign chng vo cc textboxes ca Form nh sau:
Private Sub Displayrecord() ' Assign record fields to the appropriate textboxes With myRS ' Assign field Title to textbox txtTitle txtTitle.Text = .Fields("Title") txtYearPublished.Text = .Fields("[Year Published]") txtISBN.Text = .Fields("ISBN") txtPublisherID.Text = .Fields("PubID") End With End Sub

v field Year Publshed gm c hai ch nn ta phi t tn ca field y gia hai du ngoc vung ([]). trnh b phin phc nh trong trng hp ny, khi bn t tn database field trong lc thit k mt table hy dn dnh cc ch li vi nhau, ng ri ra. Th d nh dng YearPublished thay v Year Published.

Cc nt di chuyn
Mun c cc nt Navigators tng ng vi ca mt Control Data, bn hy t ln Form 4 buttons mang tn CmdFirst, CmdPrevious, CmNext v CmdLast vi captions: <<, <, >, >>. Code cho cc nt ny cng n gin, nhng ta phi coi chng khi user mun di chuyn qu record cui cng hay record u tin. Ta phi kim tra xem EOF c tr thnh True khi user click CmdNext, hay BOF c tr thnh True khi user click CmdPrevious:
Private Sub CmdNext_Click() myRS.MoveNext ' Move to next record ' Display record details if has not gone past the last record If Not myRS.EOF Then Displayrecord ' display details of current record Else myRS.MoveLast ' Move back to last record End If End Sub Private Sub CmdPrevious_Click() myRS.MovePrevious ' Move to previous record

' Display record details if has not gone past the first record If Not myRS.BOF Then Displayrecord ' display details of current record Else myRS.MoveFirst ' Move back to first record End If End Sub Private Sub CmdFirst_Click() myRS.MoveFirst ' Move back to first record Displayrecord ' display details of current record End Sub Private Sub CmdLast_Click() myRS.MoveLast ' Move back to last record Displayrecord ' display details of current record End Sub

Khi chy chng trnh bn s thy n hin th chi tit ca Record u tin khc vi trong bi trc y v cc records c sorted:

Bn hy th dng cc Navigator buttons cy nh, l vn ca mnh xem chng lm vic c ng khng. Ti y, khng bit bn c l d user c v tnh sa i mt chi tit no trong cc textboxes, khng c record no b cp nht ha trong database khi user di chuyn t record ny n record khc. L do l cc Texboxes khng c Data Bound vi cc Fields ca Recordset.

Thm bt cc Records
Ging nh chng trnh trong bi ri, ta s thm phng tin thm (add), bt (delete) cc records. By gi bn hy vo Form 5 buttons tn: cmdEdit, cmdNew, cmdDelete, cmdUpdate v cmdCancel. Ch no trong chng trnh trc ta dng Data1.Recordset th by gi ta dng myRS. Ta s dng li Sub SetControls vi parameter Editing c tr s False hay True ty theo user ang Browse hay Edit. Trong Browse mode, cc Textboxes b Locked (kha) v cc nt cmdUpdate v cmdCancel tr nn bt lc. Trong Edit mode, cc Textboxes c unlocked (m kha) v cc nt cmdNew, cmdDelete v cmdEdit tr nn bt lc.

V y khng c Data Binding nn i cho n khi Update (cp nht ha) ta mi t Recordset vo AddNew hay Edit mode. Do ta ch cn nh l khi user edits l ang Edit mt record hin hu hay thm mt Record mi. Ta cha tr s Boolean y trong variable AddNewRecord. Nu user sp thm mt record mi th AddNewRecord = True, nu User sp Edit mt record hin hu th AddNewRecord = False. Ngoi ra, khi User sp thm mt record mi bng cch click nt New th ta phi t clear (lm trng) ht cc textboxes bng cch assign Empty string vo text property ca chng nh sau:
' If Editing existing record then AddNewRecord = False ' Else AddNewRecord = true Dim AddNewRecord As Boolean Private Sub ClearAllFields() ' Clear all the textboxes txtTitle.Text = "" txtYearPublished.Text = "" txtISBN.Text = "" txtPublisherID.Text = "" End Sub Private Sub cmdNew_Click() ' Remember that this is Adding a new record AddNewRecord = True ' Clear all textboxes ClearAllFields ' Place controls in Edit Mode SetControls (True) End Sub Private Sub CmdEdit_Click() ' Place controls in Edit Mode SetControls (True) ' Remember that this is Editing an existing record AddNewRecord = False End Sub

Nu user clicks Cancel trong khi ang edit cc textboxes, ta khng cn gi method CancelUpdate v Recordset cha b t vo AddNew hay Edit mode. y ta ch cn hin th li chi tit ca current record, tc l hy b nhng g user ang nh vo:
Private Sub CmdCancel_Click() ' Cancel update SetControls (False) ' Redisplay details or current record Displayrecord End Sub

Lc user clicks Update, bn c dp kim tra data xem c field no b b trng (nht l Primary Key ISBN bt buc phi c tr s) hay c g khng valid bng cch gi Function GoodData. Nu GoodData tr li mt tr s False th ta khng xc tin vi vic Update. Nu GoodData tr v tr s True th ta t Recordset vo AddNew hay Edit mode ty theo tr s ca Boolean variable AddNewRecord. Ging nh khi hin th chi tit ca mt Record ta phi assign tng Field vo textbox, th

by gi khi Update ta phi lm ngc li, tc l assign property Text ca tng textbox vo Record Field tng ng. Sau cng ta gi method Update ca recordset v cho cc controls tr li Browse mode:
Private Function GoodData() As Boolean ' Check Data here. If Invalid Data then GoodData = False GoodData = True End Function Private Sub CmdUpdate_Click() ' Verify all data, if Bad then do not Update If Not GoodData Then Exit Sub ' Assign record fields to the appropriate textboxes With myRS If AddNewRecord Then .AddNew ' Place Recordset in AddNew Mode Else .Edit ' Place Recordset in Edit Mode End If ' Assign text of txtTitle to field Title .Fields("Title") = txtTitle.Text .Fields("[Year Published]") = txtYearPublished.Text .Fields("ISBN") = txtISBN.Text .Fields("PubID") = txtPublisherID.Text ' Update data .Update End With ' Return controls to Browse Mode SetControls (False) End Sub

Cng v khng c Data Binding, nn khi User Delete mt record, sau khi di chuyn qua record k tip ta phi t hin th chi tit ca record nh sau:
Private Sub CmdDelete_Click() On Error GoTo DeleteErr With myRS ' Delete new record .Delete ' Move to next record .MoveNext If .EOF Then .MoveLast ' Display details of current record Displayrecord Exit Sub End With DeleteErr: MsgBox Err.Description Exit Sub End Sub

Tm mt record
Tip theo y, ta mun lit k cc sch c tiu cha mt ch hay cu no , th d nh ch "Guide". K user c th chn mt sch bng cch select tiu sch y v click nt Go. Chng trnh s locate (tm ra) record ca sch y v hin th chi tit ca n.

By gi bn hy cho vo Form mt textbox tn txtSearch v mt Image tn ImgSearch. K t mt frame tn fraSearch vo Form. ln frame ny mt listbox tn List1 hin th tiu cc sch, v hai buttons tn CmdClose v CmdGo, vi caption Close v Go. Sau khi select mt sch trong List1, user s click nt Go hin th chi tit sch y. Nu i , user s click nt Close lm bin mt frame fraSearch. Bnh thng frame fraSearch ch hin ra khi cn, nn lc u hy set property Visible ca n thnh False. Ta s cho ImgSearch hin th hnh mt ng dm nn bn hy click vo bn phi property Picture trong Properties Window chn Icon BINOCULR.ICO t folder E:\Program Files\Microsoft Visual Studio\Common\Graphics\Icons\Misc:

Ci Primary Key ca table Titles l ISBN. Khi user select mt sch ta mun bit ISBN ca sch y locate (nh ch) n trong Recordset myRS. Do trong khi thm tiu ca mt sch vo List1, ta ng thi thm ISBN ca sch y vo mt Listbox th hai tn List2. Ta ch s dng List2 sau hu trng, nn hy set property Visible ca n thnh False. Di y l code load tiu sch v ISBN vo cc Listboxes:
Private Sub ImgSearch_Click() ' Show Search Frame fraSearch.Visible = True Dim SrchRS As DAO.Recordset Dim SQLCommand As String ' Define SQL statement SQLCommand = "Select * from Titles where Title LIKE '" & "*" & txtSearch & "*" & "' ORDER BY Title" ' Fetch all records having Title containing the text pattern given by txtSearch Set SrchRS = myDB.OpenRecordset(SQLCommand) ' If Recordset is not Empty then list the books' titles in List1 If SrchRS.RecordCount > 0 Then List1.Clear ' Clear List1 ' We use List2 to contain the Primary Key ISBN corresponding to the books in List1

List2.Clear ' Clear List2 With SrchRS ' Iterate through the Recordset until EOF Do While Not SrchRS.EOF ' Display Title in List1 List1.AddItem .Fields("Title") ' Store corresponding ISBN in List2 List2.AddItem .Fields("ISBN") .MoveNext ' Move to next record in the Recordset Loop End With End If End Sub

Khi user Click ImgSearch vi text pattern l ch Guide, ta s thy hnh di y:

Trong SELECT statement bn trn ta dng operator LIKE trn text pattern, ch Guide, c wildcard character (*) hai bn. Wildcard character l ch c (hay khng c) ch g cng c. Trong trng hp ny c ngha l h c ch Guide trong tiu sch l c, khng cn bit n nm u. Ngoi ra s chn la ny Khng c Case Sensitive, tc l ch guide, Guide hay GUIDE u c c. Khi user clicks nt Go, ta s dng method FindFirst ca Recordset myRS nh ch ca record c tr s Primary Key l hng text trong List2 tng ng vi tiu dc chn trong List1 nh sau:
Private Sub CmdGo_Click() Dim SelectedISBN As String Dim SelectedIndex As Integer Dim Criteria As String ' Index of line selected by user in List1 SelectedIndex = List1.ListIndex ' Obtain corresponding ISBN in List2 SelectedISBN = List2.List(SelectedIndex) ' Define Search criteria - use single quotes for selected text Criteria = "ISBN = '" & SelectedISBN & "'" ' Locate the record, it will become the current record myRS.FindFirst Criteria ' Display details of current record Displayrecord ' Make fraSearch disappeared

fraSearch.Visible = False End Sub

Lu l trong string Criteria, v ISBN thuc loi text, ch khng phi l mt con s, nn ta phi kp n gia hai du ngoc n.

Bookmark
Khi di chuyn t record ny n record khc trong Recordset, i khi ta mun nh du v tr ca mt record c dp s tr li. Ta c th thc hin iu y bng cch ghi nh Bookmark ca Recordset. Th d khi user clicks nt Go, ta mun nh v tr ca record lc y sau ny quay tr li khi User clicks nt Go Back. Bn hy thm vo Form mt button tn CmdGoBack vi Caption Go Back. Ta s thm mt variable tn LastBookmark loi data type Variant:
Dim LastBookMark As Variant

Lc u button CmdGoBack invisible, v ch tr nn visible sau khi user clicks nt Go. Ta thm cc hng codes sau vo Sub CmdGo_Click() nh sau:
' Remember location of current record LastBookMark = myRS.BookMark CmdGoback.Visible = True

Di y l code quay tr li v tr current record trc y trong Recordset:


Private Sub CmdGoback_Click() ' Reposition record to last position myRS.BookMark = LastBookMark ' Redisplay details or current record Displayrecord End Sub

LastModified
LastModified l vi tr ca record va mi c sa i hay thm vo trong Recordset. th iu ny bn hy thm mt button invisible tn CmdLastModified vi caption l Last Modified. Button ny ch hin ra sau khi user clicks Update. Bt c lc no bn Click nt CmdLastModified, record mi va c sa i hay thm vo s hin th:
Private Sub CmdLastModified_Click() ' Reposition record to last position myRS.BookMark = myRS.LastModified ' Redisplay details or current record Displayrecord End Sub

Di y l hnh ca Form lc ang c thit k:

Ta s hc k thut ADO (ActiveX Data Object) trong bi ti.

You might also like