-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDAO.bas
1483 lines (1024 loc) · 39 KB
/
DAO.bas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Attribute VB_Name = "DAO"
'---------------------------------------------------------------------------------------
' Module : DAO
' DateTime : 4/10/2002 14:34
' Author : Avaneesh Dvivedi
' Purpose :Everything you want to do with DAO. Every functions
' are included. DAO still being used by many programmers.
' for further details check out my web site
' http://www.tax-publishers.com/advivedi
'---------------------------------------------------------------------------------------
Option Explicit
'The following code listings show how to open (and then close) a shared, read-only database using DAO and ADO.
'DAO
Sub DAOOpenJetDatabaseReadOnly()
Dim db As DAO.Database
' Open shared, read-only.
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb", False, True)
db.Close
End Sub
'The following listings demonstrate how to override the Page Timeout setting of the engine and open a database using that setting.
'DAO
Sub DAOSetJetDBOption()
Dim db As DAO.Database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
DBEngine.SetOption dbPageTimeout, 4000
db.Close
'The following table lists the values that can be set with DAO's SetOption method and the corresponding property to use with ADO.
'DAO constant ADO property
'dbPageTimeout Jet OLEDB:Page Timeout
'dbSharedAsyncDelay Jet OLEDB:Shared Async Delay
'dbExclusiveAsyncDelay Jet OLEDB:Exclusive Async Delay
'dbLockRetry Jet OLEDB:Lock Retry
'dbUserCommitSync Jet OLEDB:User Commit Sync
'dbImplicitCommitSync Jet OLEDB:Implicit Commit Sync
'dbMaxBufferSize Jet OLEDB:Max Buffer Size
'dbMaxLocksPerFile Jet OLEDB:Max Locks Per File
'dbLockDelay Jet OLEDB:Lock Delay
'dbRecycleLVs Jet OLEDB:Recycle Long-Valued Pages
'dbFlushTransactionTimeout Jet OLEDB:Flush Transaction Timeout
End Sub
'Share-Level (Password Protected) Databases
'The following listings demonstrate how to open a Microsoft Jet database that has been secured at the share level.
'DAO
Sub DAOOpenDBPasswordDatabase()
Dim db As DAO.Database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb", _
False, False, ";pwd=password")
db.Close
'In DAO, the Connect parameter of the OpenDatabase method sets the database password when opening a database. With ADO, the Microsoft Jet Provider connection property Jet OLEDB:Database Password sets the password instead
End Sub
'Opening a Database with User-Level Security
'These next listings demonstrate how to open a database that is secured at the user level using a workgroup information file named "system.mdw".
'DAO
Sub DAOOpenSecuredDatabase()
Dim wks As DAO.Workspace
Dim db As DAO.Database
DBEngine.SystemDB = _
"C:\Program Files\Microsoft Office\Office\SYSTEM.MDW"
Set wks = DBEngine.CreateWorkspace("", "Admin", "")
Set db = wks.OpenDatabase(".\NorthWind.mdb")
db.Close
wks.Close
End Sub
'External Databases
'The Microsoft Jet database engine can be used to access other database files, spreadsheets, and textual data stored in tabular format through installable ISAM drivers.
'The following listings demonstrate how to open a Microsoft Excel 2000 spreadsheet first using DAO, then using ADO and the Microsoft Jet provider.
'DAO
Sub DAOOpenISAMDatabase()
Dim db As DAO.Database
Set db = DBEngine.OpenDatabase(".\Sales.xls", _
False, False, "Excel 8.0;")
db.Close
'The DAO and ADO code for opening an external database is similar. In both examples, the name of the external file (Sales.xls) is used in place of a Microsoft Jet database file name. With both DAO and ADO you must also specify the type of external database you are opening, in this case, an Excel 2000 spreadsheet. With DAO, the database type is specified in the Connect argument of the OpenDatabase method. The database type is specified in the Extended Properties property of the Connection with ADO. The following table lists the strings to use to specify which ISAM to open.
'Database String
'dBASE III dBASE III;
'dBASE IV dBASE IV;
'dBASE 5 dBASE 5.0;
'Paradox 3.x Paradox 3.x;
'Paradox 4.x Paradox 4.x;
'Paradox 5.x Paradox 5.x;
'Excel 3.0 Excel 3.0;
'Excel 4.0 Excel 4.0;
'Excel 5.0/Excel 95 Excel 5.0;
'Excel 97 Excel 97;
'Excel 2000 Excel 8.0;
'HTML Import HTML Import;
'HTML Export HTML Export;
'Text Text;
'ODBC ODBC;
'DATABASE=database;
'UID=user;
'PWD=password;
'DSN = DataSourceName
End Sub
'The Current Microsoft Access Database
'When you open Microsoft Access, you are opening a Microsoft Jet database. When writing code within Access, you may often want to use the same connection to Microsoft Jet as Access is using. To allow you to do this, Microsoft Access 2000 exposes two mechanisms: CurrentDB() and CurrentProject.Connection allow you to get a DAO Database object and an ADO Connection object, respectively, for the database Access currently has open.
'The following listings demonstrate how to get a reference to the database currently open in Microsoft Access.
Sub DAOGetCurrentDatabase()
Dim db As DAO.Database
Set db = CurrentDb()
End Sub
'The following code demonstrates how to open a Microsoft Jet database for shared, updateable access. Then the code immediately closes the database because this code is for demonstration purposes.
Sub DAOOpenJetDatabase()
Dim db As DAO.Database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
db.Close
End Sub
'The following code listings show how to open (and then close) a shared, read-only database using DAO and ADO.
Sub DAOOpenRecordset()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim fld As DAO.Field
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Open the Recordset
Set rst = db.OpenRecordset _
("SELECT * FROM Customers WHERE Region = 'WA'", _
dbOpenForwardOnly, dbReadOnly)
' Print the values for the fields in
' the first record in the debug window
For Each fld In rst.Fields
Debug.Print fld.Value & ";";
Next
Debug.Print
' Close the recordset
rst.Close
End Sub
Sub DAOMoveNext()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim fld As DAO.Field
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Open the Recordset
Set rst = db.OpenRecordset _
("SELECT * FROM Customers WHERE Region = 'WA'", _
dbOpenForwardOnly, dbReadOnly)
' Print the values for the fields in
' the first record in the debug window
Do Until rst.EOF
For Each fld In rst.Fields
Debug.Print fld.Value & ";";
Next
Debug.Print
rst.MoveNext
Loop
' Close the recordset
rst.Close
End Sub
Sub DAOGetCurrentPosition()
Dim db As DAO.Database
Dim rst As DAO.Recordset
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Open the Recordset
Set rst = db.OpenRecordset("SELECT * FROM Customers", _
dbOpenDynaset)
' Print the absolute position
Debug.Print rst.AbsolutePosition
' Move to the last record
rst.MoveLast
' Print the absolute position
Debug.Print rst.AbsolutePosition
' Close the recordset
rst.Close
End Sub
Sub DAOFindRecord()
Dim db As DAO.Database
Dim rst As DAO.Recordset
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Open the Recordset
Set rst = db.OpenRecordset("Customers", dbOpenDynaset)
' Find the first customer whose country is USA
rst.FindFirst "Country = 'USA'"
' Print the customer id's of all customers in the USA
Do Until rst.NoMatch
Debug.Print rst.Fields("CustomerId").Value
rst.FindNext "Country = 'USA'"
Loop
' Close the recordset
rst.Close
End Sub
Sub DAOSeekRecord()
Dim db As DAO.Database
Dim rst As DAO.Recordset
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Open the Recordset
Set rst = db.OpenRecordset("Order Details", dbOpenTable)
' Select the index used to order the data in the recordset
rst.Index = "PrimaryKey"
' Find the order where OrderId = 10255 and ProductId = 16
rst.Seek "=", 10255, 16
' If a match is found print the quantity of the order
If Not rst.NoMatch Then
Debug.Print rst.Fields("Quantity").Value
End If
' Close the recordset
rst.Close
End Sub
Sub DAOFilterRecordset()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim rstFlt As DAO.Recordset
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Open the Recordset
Set rst = db.OpenRecordset("Customers", dbOpenDynaset)
' Set the Filter to be used for subsequent recordsets
rst.Filter = "Country='USA' And Fax Is Not Null"
' Open the filtered recordset
Set rstFlt = rst.OpenRecordset()
Debug.Print rstFlt.Fields("CustomerId").Value
' Close the recordsets
rst.Close
rstFlt.Close
End Sub
Sub DAOSortRecordset()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim rstSort As DAO.Recordset
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Open the Recordset
Set rst = db.OpenRecordset("Customers", dbOpenDynaset)
' Sort the recordset based on Country and Region both in
' ascending order
rst.Sort = "Country, Region"
' Open the sorted recordset
Set rstSort = rst.OpenRecordset()
Debug.Print rstSort.Fields("CustomerId").Value
' Close the recordsets
rst.Close
rstSort.Close
End Sub
Sub DAOAddRecord()
Dim db As DAO.Database
Dim rst As DAO.Recordset
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Open the Recordset
Set rst = db.OpenRecordset _
("SELECT * FROM Customers", dbOpenDynaset)
' Add a new record
rst.AddNew
' Specify the values for the fields
rst!CustomerId = "HENRY"
rst!CompanyName = "Henry's Chop House"
rst!ContactName = "Mark Henry"
rst!ContactTitle = "Sales Representative"
rst!Address = "40178 NE 8th Street"
rst!City = "Bellevue"
rst!Region = "WA"
rst!PostalCode = "98107"
rst!Country = "USA"
rst!Phone = "(425) 555-9876"
rst!Fax = "(425) 555-8908"
' Save the changes you made to the
' current record in the Recordset
rst.Update
' For this example, just print out
' CustomerId for the new record
' Position recordset on new record
rst.Bookmark = rst.LastModified
Debug.Print rst!CustomerId
' Close the recordset
rst.Close
End Sub
Sub DAOUpdateRecord()
Dim db As DAO.Database
Dim rst As DAO.Recordset
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Open the Recordset
Set rst = db.OpenRecordset _
("SELECT * FROM Customers WHERE CustomerId = 'LAZYK'", _
dbOpenDynaset)
' Put the Recordset in Edit Mode
rst.Edit
' Update the Contact name of the
' first record
rst.Fields("ContactName").Value = "New Name"
' Save the changes you made to the
' current record in the Recordset
rst.Update
' Close the recordset
rst.Close
End Sub
Sub DAOReadMemo()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim sNotes As String
Dim sChunk As String
Dim cchChunkReceived As Long
Dim cchChunkRequested As Long
Dim cchChunkOffset As Long
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Open the Recordset
Set rst = db.OpenRecordset _
("SELECT Notes FROM Employees", dbOpenDynaset)
' Initialize offset
cchChunkOffset = 0
' cchChunkRequested artifically set low at 16
' to demonstrate looping
cchChunkRequested = 16
' Loop through as many chunks as it takes
' to read the entire BLOB into memory
Do
' Temporarily store the next chunk
sChunk = rst!Fields("Notes").GetChunk _
(cchChunkOffset, cchChunkRequested)
' Check how much we got
cchChunkReceived = Len(sChunk)
' Adjust offset for next iteration
cchChunkOffset = cchChunkOffset + cchChunkReceived
' If we got anything,
' concatenate it to the main BLOB
If cchChunkReceived > 0 Then
sNotes = sNotes & sChunk
End If
Loop While cchChunkReceived = cchChunkRequested
' For this example, print the value of
' the Notes field for just the first record
Debug.Print sNotes
' Close the recordset
rst.Close
End Sub
'The following listings demonstrate how to update binary data in an OLE object field without using the GetChunk or AppendChunk methods.
Sub DAOUpdateBLOB()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim rgPhoto() As Byte
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Open the Recordset
Set rst = db.OpenRecordset( _
"SELECT Photo FROM Employees", dbOpenDynaset)
' Get the first photo
rgPhoto = rst.Fields("Photo").Value
' Move to the next record
rst.MoveNext
' Put the Recordset in Edit Mode
rst.Edit
' Copy the photo into the next record
rst.Fields("Photo").Value = rgPhoto
' Save the changes you made to the
' current record in the Recordset
rst.Update
' Close the recordset
rst.Close
End Sub
'Executing a Non-Parameterized Stored Query
'A non-parameterized stored query is an SQL statement that has been saved in the database and does not require that additional variable information be specified in order to execute. The following listings demonstrate how to execute such a query.
Sub DAOExecuteQuery()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim fld As DAO.Field
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Open the Recordset
Set rst = db.OpenRecordset("Products Above Average Price", _
dbOpenForwardOnly, dbReadOnly)
' Display the records in the
' debug window
Do Until rst.EOF
For Each fld In rst.Fields
Debug.Print fld.Value & ";";
Next
Debug.Print
rst.MoveNext
Loop
' Close the recordset
rst.Close
End Sub
'Executing a Parameterized Stored Query
'A parameterized stored query is an SQL statement that has been saved in the database and requires that additional variable information be specified in order to execute. The code below shows how to execute such a query.
Sub DAOExecuteParamQuery()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
Dim fld As DAO.Field
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Get the QueryDef from the
' QueryDefs collection
Set qdf = db.QueryDefs("Sales by Year")
' Specify the parameter values
qdf.Parameters _
("Forms!Sales by Year Dialog!BeginningDate") = #8/1/1997#
qdf.Parameters _
("Forms!Sales by Year Dialog!EndingDate") = #8/31/1997#
' Open the Recordset
Set rst = qdf.OpenRecordset(dbOpenForwardOnly, dbReadOnly)
' Display the records in the
' debug window
Do Until rst.EOF
For Each fld In rst.Fields
Debug.Print fld.Value & ";";
Next
Debug.Print
rst.MoveNext
Loop
' Close the recordset
rst.Close
End Sub
'Executing Bulk Operations
'The ADO Command object's Execute method can be used for row-returning queries, as shown in the previous section, as well as for non row-returning queriesalso known as bulk operations. The following code examples demonstrate how to execute a bulk operation in both DAO and ADO.
Sub DAOExecuteBulkOpQuery()
Dim db As DAO.Database
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Execute the query
db.Execute "UPDATE Customers SET Country = 'United States' " & _
"WHERE Country = 'USA'"
Debug.Print "Records Affected = " & db.RecordsAffected
' Close the database
db.Close
End Sub
'Creating a Database
'Before tables or other objects can be defined, the database itself must be created. The following code creates and opens a new Microsoft Jet database.
Sub DAOCreateDatabase()
Dim db As DAO.Database
Set db = DBEngine.CreateDatabase(".\New.mdb", dbLangGeneral)
'
'In the DAO code above, the Locale parameter is specified as dbLangGeneral. In the ADOX code, locale is not explicitly specified. The default locale for the Microsoft Jet Provider is equivalent to dbLangGeneral. Use the ADO Locale Identifier property to specify a different locale.
'In DAO, CreateDatabase also can take a third Options parameter, specifying information for encrytion and database version. For example, the following line is used to create an encrypted, version 1.1 Microsoft Jet database:
'
' Set db = DBEngine.CreateDatabase(".\New.mdb", dbLangGeneral, _
' dbEncrypt + dbVersion11)
'
End Sub
'The following code demonstrates how to print the name of every table in the database by looping through the DAO TableDefs collection and the ADOX Tables collection.
Sub DAOListTables()
Dim db As DAO.Database
Dim tbl As DAO.TableDef
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Loop through the tables in the database and print their name
For Each tbl In db.TableDefs
Debug.Print tbl.Name
Next
End Sub
Sub DAOCreateTable()
Dim db As DAO.Database
Dim tbl As DAO.TableDef
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Create a new TableDef object.
Set tbl = db.CreateTableDef("Contacts")
With tbl
' Create fields and append them to the new TableDef object.
' This must be done before appending the TableDef object to
' the TableDefs collection of the Database.
.Fields.Append .CreateField("ContactName", dbText)
.Fields.Append .CreateField("ContactTitle", dbText)
.Fields.Append .CreateField("Phone", dbText)
.Fields.Append .CreateField("Notes", dbMemo)
.Fields("Notes").Required = False
End With
' Add the new table to the database.
db.TableDefs.Append tbl
db.Close
End Sub
Sub DAOCreateAttachedJetTable()
Dim db As DAO.Database
Dim tbl As DAO.TableDef
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Create a new TableDef object.
Set tbl = db.CreateTableDef("Authors")
' Set the properties to create the link
tbl.Connect = ";DATABASE=.\Pubs.mdb;pwd=password;"
tbl.SourceTableName = "authors"
' Add the new table to the database.
db.TableDefs.Append tbl
db.Close
End Sub
Sub DAOCreateAttachedODBCTable()
Dim db As DAO.Database
Dim tbl As DAO.TableDef
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Create a new TableDef object.
Set tbl = db.CreateTableDef("Titles")
' Set the properties to create the link
tbl.Connect = "ODBC;DSN=ADOPubs;UID=sa;PWD=;"
tbl.SourceTableName = "titles"
' Add the new table to the database.
db.TableDefs.Append tbl
db.Close
End Sub
Sub DAOCreateAutoIncrColumn()
Dim db As DAO.Database
Dim tbl As DAO.TableDef
Dim fld As DAO.Field
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Get the Contacts table
Set tbl = db.TableDefs("Contacts")
' Create the new auto increment column
Set fld = tbl.CreateField("ContactId", dbLong)
fld.Attributes = dbAutoIncrField
' Add the new table to the database.
tbl.Fields.Append fld
db.Close
End Sub
'The next example shows how to update an existing linked table to refresh the link. This involves updating the connection string for the table and then resetting the Jet OLEDB:CreateLink property to tell Microsoft Jet to reestablish the link.
Sub DAORefreshLinks()
Dim db As DAO.Database
Dim tbl As DAO.TableDef
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
For Each tbl In db.TableDefs
' Check to make sure table is a linked table.
If (tbl.Attributes And dbAttachedTable) Then
tbl.Connect = "MS Access;PWD=NewPassWord;" & _
"DATABASE=.\NewPubs.mdb"
tbl.RefreshLink
End If
Next
End Sub
Sub DAOCreateIndex()
Dim db As DAO.Database
Dim tbl As DAO.TableDef
Dim idx As DAO.Index
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
Set tbl = db.TableDefs("Employees")
' Create Index object append Field object to the Index object.
Set idx = tbl.CreateIndex("CountryIndex")
idx.Fields.Append idx.CreateField("Country")
' Append the Index object to the
' Indexes collection of the TableDef.
tbl.Indexes.Append idx
db.Close
End Sub
Sub DAOCreatePrimaryKey()
Dim db As DAO.Database
Dim tbl As DAO.TableDef
Dim idx As DAO.Index
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
Set tbl = db.TableDefs("Contacts")
' Create the Primary Key and append table columns to it.
Set idx = tbl.CreateIndex("PrimaryKey")
idx.Primary = True
idx.Fields.Append idx.CreateField("ContactId")
' Append the Index object to the
' Indexes collection of the TableDef.
tbl.Indexes.Append idx
db.Close
End Sub
Sub DAOCreateForeignKey()
Dim db As DAO.Database
Dim rel As DAO.Relation
Dim fld As DAO.Field
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' This key already exists in the Northwind database.
' For the purposes of this example, we're going to
' delete it and then recreate it
db.Relations.Delete "CategoriesProducts"
' Create the relation
Set rel = db.CreateRelation()
rel.Name = "CategoriesProducts"
rel.Table = "Categories"
rel.ForeignTable = "Products"
' Create the field the tables are related on
Set fld = rel.CreateField("CategoryId")
' Set ForeignName property of the field to the name of
' the corresponding field in the primary table
fld.ForeignName = "CategoryId"
rel.Fields.Append fld
' Append the relation to the collection
db.Relations.Append rel
End Sub
Sub DAOCreateForeignKeyCascade()
Dim db As DAO.Database
Dim rel As DAO.Relation
Dim fld As DAO.Field
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' This key already exists in the Northwind database.
' For the purposes of this example, we're going to
' delete it and then recreate it
db.Relations.Delete "CategoriesProducts"
' Create the relation
Set rel = db.CreateRelation()
rel.Name = "CategoriesProducts"
rel.Table = "Categories"
rel.ForeignTable = "Products"
' Specify cascading updates and deletes
rel.Attributes = dbRelationUpdateCascade Or _
dbRelationDeleteCascade
' Create the field the tables are related on
Set fld = rel.CreateField("CategoryId")
' Set ForeignName property of the field to the name of
' the corresponding field in the primary table
fld.ForeignName = "CategoryId"
rel.Fields.Append fld
' Append the relation to the collection
db.Relations.Append rel
End Sub
Sub DAOCreateQuery()
Dim db As DAO.Database
Dim qry As DAO.QueryDef
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Create query
Set qry = db.CreateQueryDef("AllCategories", _
"SELECT * FROM Categories")
db.Close
End Sub
Sub DAOCreateParameterizedQuery()
Dim db As DAO.Database
Dim qry As DAO.QueryDef
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Create query
Set qry = db.CreateQueryDef("Employees by Region", _
"PARAMETERS [prmRegion] TEXT(255);" & _
"SELECT * FROM Employees WHERE Region = [prmRegion]")
db.Close
End Sub
Sub DAOModifyQuery()
Dim db As DAO.Database
Dim qry As DAO.QueryDef
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Get the query
Set qry = db.QueryDefs("Employees by Region")
' Update the SQL and save the updated query
qry.SQL = "PARAMETERS [prmRegion] TEXT(255);" & _
"SELECT * FROM Employees WHERE Region = [prmRegion] " & _
"ORDER BY City"
db.Close
End Sub
Sub DAOCreateSQLPassThrough()
Dim db As DAO.Database
Dim qry As DAO.QueryDef
' Open the database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb")
' Create query
Set qry = db.CreateQueryDef("Business Books", _
"SELECT * FROM Titles WHERE Type = 'business'")
qry.Connect = "ODBC;DSN=ADOPubs;UID=sa;PWD=;"
qry.ReturnsRecords = True
db.Close
End Sub
Sub DAOChangePassword()
Dim wks As Workspace
Dim usr As DAO.User
' Open the workspace, specifying the system database to use
DBEngine.SystemDB = _
"C:\Program Files\Microsoft Office\Office\SYSTEM.MDW"
Set wks = DBEngine.CreateWorkspace("", "Admin", "")
' Change the password for the user Admin
wks.Users("Admin").NewPassword "", "password"
End Sub
'The following code shows how to change the database password for enabling security at the share level.
Sub DAOChangeDatabasePassword()
' Make sure there isn't already a file with the
' name of the compacted database.
If Dir(".\NewNorthWind.mdb") <> "" Then _
Kill ".\NewNorthWind.mdb"
' Basic compact - creating new database named newnwind
DBEngine.CompactDatabase ".\NorthWind.mdb", _
".\NewNorthWind.mdb", , , ";pwd=password;"
' Delete the original database
Kill ".\NorthWind.mdb"
' Rename the file back to the original name
Name ".\NewNorthWind.mdb" As ".\NorthWind.mdb"
End Sub
'Alternatively, the DAO code could be rewritten to use the NewPassword method of the Database object.
Sub DAOChangeDatabasePassword2()
Dim db As DAO.Database
Set db = DBEngine.OpenDatabase(".\NorthWind.mdb", True)
db.NewPassword "", "password"
db.Close
'A similar mechanism is not currently available in JRO or ADOX. You must use the CompactDatabase method in order to change the database password.
End Sub
Sub DAOCreateUser()
Dim wks As DAO.Workspace
' Open a workspace
DBEngine.SystemDB = _