“Hello World” is the first code example in the now-classic book, The C Programming Language, by Brian Kernighan and Dennis Ritchie. The following examples show you how to perform a simple task with DAO using Hello World. But instead of printing a string variable to the screen, our version searches for a value in a table and retrieves a message for display.
The NorthwindTables database includes a table with one text field, Greeting, that contains different greetings. The following table shows the data that the Greeting field contains.
Greeting |
Bonjour |
Buenos dias |
Hello World! |
Hi |
Howdy |
The following code shows one way to retrieve the greeting. In this example, strDbPath
is the path to the NorthwindTables database, and strGreeting
is the string for which you are searching:
Dim dbs As Database Dim rst As Recordset Set dbs = OpenDatabase(strDbPath) Set rst = dbs.OpenRecordset("Greetings", dbOpenTable) With rst .Index = "GreetingIndex" .Seek "=", strGreeting If Not .NoMatch Then MsgBox !Greeting Else MsgBox "Could not find " & strGreeting & "." End If End With Set rst = Nothing Set dbs = Nothing
The following explains what’s happening when this code runs:
dbs
and rst
are declared. These are used to point to the actual Database and Recordset objects used in the example.strDbPath
, and assign the variable dbs to the database. If you install the sample databases to the default folder, then the value of strDbPath
is "C:\JetBook\Samples\NorthwindTables.mdb"
. If you open NorthwindTables.mdb in Microsoft Access and paste this code into a module, you can set the Database object variable by using the CurrentDb function."GreetingIndex"
. This index exists on the Greeting field in the Greetings table.strGreeting
. You can experiment with searching for other values in the table by using the Seek method to look for other values in the table.The end result is a program that displays one of the greetings (such as “Hello World!”) stored in the Greetings table of the NorthwindTables database. The key concepts in this example are:
As you progress through the rest of this chapter, you’ll see how these elements work together to form a cohesive DAO object model that provides flexible access to the objects and data in your database.