Connecting Tech Pros Worldwide Forums | Help | Site Map

DAO or ADO - Why Not Both?

ADezii's Avatar
Expert
 
Join Date: Apr 2006
Location: Philadelphia
Posts: 5,217
#1   Mar 31 '07
Whether to use DAO or ADO is sometimes a tricky question. By simply changing the value of a compile-time constant, USEDAO, you can selectively choose to use either Object Library within you code. Here is the procedure to follow:

1. Set References to both the DAO and ADO Object Libraries. In my specific case, this would be:
Expand|Select|Wrap|Line Numbers
  1. Microsoft DAO 3.6 Object Library
  2. Microsoft ActiveX Data Objects 2.1 Object Library 
2. Declare your compile-time constant within the General Declarations Section of your Form's Code Module:
Expand|Select|Wrap|Line Numbers
  1. #Const USEDAO = True        'will use DAO, for now 
3. Sample demonstration code:
Expand|Select|Wrap|Line Numbers
  1. Dim strSQL As String
  2.  
  3. strSQL = "SELECT * FROM Employees ORDER BY [LastName]"
  4.  
  5. #If USEDAO Then     '#Const USEDAO = True
  6.   Dim MyDB As DAO.Database, MyRS As DAO.Recordset
  7.   Set MyDB = CurrentDb()
  8.   Set MyRS = MyDB.OpenRecordset(strSQL, dbOpenSnapshot)
  9.  
  10.   Do While Not MyRS.EOF
  11.     'Example of Recordset processing
  12.     Debug.Print MyRS![FirstName] & " " & MyRS![LastName]
  13.     MyRS.MoveNext
  14.   Loop
  15. #Else     '#Const USEDAO = False, USE ADO
  16.   Dim MyRS As ADODB.Recordset
  17.   Set MyRS = New ADODB.Recordset
  18.  
  19.   Set MyRS.ActiveConnection = CurrentProject.Connection
  20.   With MyRS
  21.     .CursorType = adOpenStatic
  22.     .LockType = adLockReadOnly
  23.     .Open strSQL
  24.   End With
  25.  
  26.   'You can also use the single line syntax
  27.   'MyRS.Open strSQL, CurrentProject.Connection, adOpenKeyset, adLockReadOnly, adCmdText
  28.  
  29.   Do While Not MyRS.EOF
  30.     'Example of Recordset processing
  31.     Debug.Print MyRS![FirstName] & " " & MyRS![LastName]
  32.     MyRS.MoveNext
  33.   Loop
  34. #End If 
4. If you wanted to use ADO for this exercise, change the compile-time constant to False:
Expand|Select|Wrap|Line Numbers
  1. #Const USEDAO = False        'will use ADO now 



Reply