Using Microsoft Visual C++ and DAO

Data Access Objects (DAO), the programmatic interface to Microsoft Jet, were originally designed for use with Microsoft Visual Basic and Microsoft Access Basic. With the advent of OLE Automation, it is now possible to write C++ code that uses DAO.

As of Microsoft Jet 3.0, the DAO DLL is an OLE Automation in-process server containing an embedded type library. With the type library, client programs can query the server for descriptions of exposed objects via the OLE IDispatch interface. This process can be tedious, however, so DAO C++ coding has now been simplified by the development of three types of DAO C++ coding:

  • DAO OLE Automation interfaces — DAO provides a vtable-based implementation of OLE Automation. The DAO Software Development Kit (SDK) provides header files describing the vtable interfaces for DAO, eliminating the need to go through the IDispatch mechanism. After an instance of the DBEngine object has been initially created, instances of objects are created through their parent objects, using the DAO object hierarchy. Otherwise, these objects are typical OLE Component Object Model (COM) objects; therefore, the application programmer is responsible for explicitly releasing the objects.

    For information on using OLE Automation, see the OLE 2 Programmer’s Reference.

  • dbDAO classes — If you are familiar with Microsoft Visual Basic, the DAO interfaces will be familiar and will require only a small amount of OLE COM knowledge. The dbDAO classes will be helpful because they:
    • Handle reference counting (AddRef and Release), support dynamic allocation and deallocation of objects, and provide full collection support. They also use native C++ data types where possible, or standard OLE variants.

    • Require only a small amount of C++ knowledge since the syntax of the C++ calls is very similar to Visual Basic.

    • Provide support for bulk fetching directly into your data structures.

    Like the DAO interfaces, the dbDAO classes expose the full functionality of DAO properties and methods. The dbDAO classes were designed to incur the lowest possible overhead short of programming directly to the OLE Automation object. They are part of the DAO SDK.

  • MFC DAO classes — As of Visual C++ 4.0, DAO functionality is accessible through the Microsoft Foundation Classes (MFC). Based on the CRecordset classes that were written for ODBC, the CDAORecordset classes provide similar functionality using a similar design paradigm. For more information on using the MFC DAO classes, see the VC++ 4.0 MFC documentation.

Which DAO C++ Classes to Use?

If you are familiar with OLE COM programming, then the DAO interfaces may be all you need. Even so, programming with these interfaces requires the declaration of many temporary variables in order to work down the DAO hierarchy to the object you want to work with. This creates many lines of code in itself and each of these objects must be explicitly released by the programmer, which requires additional tracking.

For the additional overhead of a 190K DLL, the dbDAO classes enable you to write more concise code, with no need to keep track of object lifetimes. Conveniences like the classes that handle variants (often the required type used by DAO properties and methods) make programming much easier. Rather than filling out the VARIANT structure, you can simply cast the variable to the appropriate class.

The MFC DAO classes are fully integrated with the MFC wizards and the general MFC object structure. If you are already familiar with MFC, or if you're writing simple database applications that you'd like to easily integrate into your existing MFC-based code, then this is the way for you. If you're more experienced with programming DAO from Visual Basic, then getting started with the dbDAO classes will require less time.


Using the dbDAO Classes

The intent of the dbDAO classes is to make the resulting DAO C++ code as similar to equivalent Microsoft Visual Basic code as possible. Fundamental DAO concepts such as properties, methods, and collections are supported by the dbDAO classes.

The following procedure, taken from the Employee example in the DAO SDK, illustrates how to call dbDAO from your application. This procedure displays a dialog box (using Microsoft Foundation Classes (MFC)) that prompts for the location of the Northwind database. After the user enters the location of Nwind.mdb, a recordset based on the Employees table is opened. If the Employees table cannot be opened, an error is displayed. (The dbDAO code is nested in a try-catch block.)

BOOL CDAOEMP2Doc::ConnectToDatabase()
{
   CFileDialog   cOpenFile(
            TRUE,
            _T("MDB"),
            _T("employee.mdb"),
            OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
            (_T("Access Files (*.mdb) |*.mdb ||")));

   /* Get the location of database (assume it's the
      Employee example) */
   cOpenFile.DoModal();

   /* The following was declared in class CDAOEMP2Doc:
   CdbDBEngine    m_cDBEngine;
   CdbDatabase      m_cNWDatabase;
   CdbRecordset   m_cEmpRecordSet;
   */
   try
      {
      m_cNWDatabase = m_cDBEngine.OpenDatabase(
            cOpenFile.m_ofn.lpstrFile);
      m_cEmpRecordSet =
         m_cNWDatabase.OpenRecordset(_T("Employees"),
            dbOpenDynaset);
      }

   catch (CdbException e)
      {
      CdbLastOLEError exError;
      TCHAR szBuf[256];

      wsprintf(szBuf, _T("Error 0x%lx : %s\n"),
         e.m_hr, (LPCTSTR) exError.GetDescription());
      AfxMessageBox(szBuf);
      }

   return TRUE;
}

Although the actual DAO code in this example amounts to a couple lines, this is a typical dbDAO call. The following sections examine what is going on here in greater detail.

dbDAO Syntax

The table below demonstrates how syntactically similar the above dbDAO code (with lengthy argument names and macro decorations removed) is to Visual Basic.

dbDAO | Visual Basic
CdbDBEnginee; CdbDatabased; CdbRecordsetr; d = e.OpenDatabase("nwind.mdb"); r = d.OpenRecordset("Employees"); | Dim d as Database Dim r as Recordset Set d = OpenDatabase("nwind.mdb") Set r = d.OpenRecordset("Employees")

One notable difference is that for dbDAO, declaring a variable of class CdbDBEngine must be the first DAO call. This declaration calls the constructor function that creates an instance of the CdbDBEngine object. For more information, see Initializing CdbDBEngine.

Other than language differences — regarding how to type variables, for example — there are some general differences in the way DAO properties, methods, and collections appear in code, as detailed in the following sections.

Properties

Properties in the dbDAO classes are defined differently from the way they are defined in Visual Basic. The PropName type library property, for example, is exposed as two methods: GetPropName and SetPropName. If the property is read-only, then only the Get method is exposed. Likewise, if the property is write-only, then only the Set method is exposed. The Get method takes no arguments and returns the value of the property, using the appropriate C data type where possible. The Set method takes a single argument — the new value to which you want to set the property — again using the appropriate C data type where possible.

For example, the Name property of an object is mapped to the GetName and SetName methods. Therefore, its C prototypes are as follows:

CString      GetName (VOID);
VOID         SetName (LPCTSTR pstr);

Variants

Some properties return data of various types. The most obvious of these are the Value properties of Field objects. These have to return variants because the data type of the return value isn’t known until run time.

Default Properties

Visual Basic has default properties. For example, the code

a = rs!FirstName

is equivalent to

a = rs!FirstName.Value

Here, Value is the default property of the Field object. Because C++ has no equivalent syntax, you have to ask for the default property by name:

a = rs.Fields["FirstName"].GetValue();

For this particular call, note that the performance of this code could be improved by using the dbDAO GetField method.

Methods

Visual Basic methods map directly to methods in the dbDAO classes. Visual Basic methods that take optional arguments may also omit any or all optional arguments in these classes. If you omit an optional argument, a default value is supplied for the argument.

Methods take C types as arguments rather than the more common VARIANT data type used in the OLE classes and VBA. See the individual method prototypes in DBDAO.H for details.

Collections

The dbDAO classes emulate Visual Basic’s collections by providing member variables that point to collections. As with default values, there is no automatic lookup syntax, which means you have to use an explicit Item method. This method is overloaded to allow you to specify either an ordinal or string index in the collection.

Automatic construction and destruction of the these references means that statements like

d.m_Tabledefs.Item(i).Name

are legal and result in the correct allocation of the referenced Item (a TableDef object in this case), and its deallocation when the reference is complete. Of course, for repeated access, it is better to declare an explicit reference, but for one-time use, this is a convenient way to retrieve collection values.

A convenient shorthand for specifying an item in a collection is to use the [ ] operator. The same statement would then be:

d.m_Tabledefs[i].Name

Note If you use reference fields by ordinal, cast the index as LONG to prevent the compiler from interpreting “0” as NULL (as shown in the ConnectToDatabase function in the Employee example).


Initializing CdbDBEngine

The CdbDBEngine class initializes the DAO DBEngine object. This is different from Microsoft Visual Basic. There are two constructors, as follows:

  • Both constructors call CoCreateInstance to create an instance of the DBEngine object and obtain a DAODBEngine interface pointer (the underlying OA interface as defined in dbdaoint.h). The same constructor allows you to add an additional reference to an existing instance of the DBEngine.

  • The other constructor actually takes five parameters, allowing the user to specify the default user, the default password, the IniPath, whether the DBEngine object is private or shared, and whether to start the engine on construction. Once the engine is started, these properties cannot be modified.

Each private engine is a new instance of DAO. A shared engine is common across all instances, enabling them to share open workspaces, databases, recordsets, and so on.

If you don't start the engine on construction, there is a Start method that starts it.

Before invoking the Start method, you can override the default Registry key by setting the IniPath property and override the default workgroup information file by setting the SystemDB property.


GetRows and GetRowsEx Methods

The dbDAO classes support the GetRows method for fetching multiple rows of data in one call. Like the Microsoft Visual Basic version, GetRows returns the data as variants.

The GetRowsEx method is a performance improvement by dbDAO and Microsoft Foundation Classes (MFC) DAO to avoid the necessity to retrieve all data as variants and then convert to native types. GetRowsEx does not exist in Visual Basic DAO.

Important The underlying ICDAORecordset::GetRows method might not be supported in future versions of DAO; however, the MFC and dbDAO classes that use this method will continue to be supported.

Using the dbDAO GetRows Method

The GetRows method takes one parameter, the number of rows to fetch, and returns the row data as variants. Unlike in Visual Basic, you cannot simply use subscripts to indicate the array field in a variant. Rather, the data is returned as an OLE SafeArray. The parray member of the variant points to an array desciptor. Individual fields are accessed by calling SafeArrayGetElement. For more information on using the SafeArray datatype, see the OLE documentation.

The following code from the GetRows sample shows how to use GetRows. Note that the table schema is known a priori, allowing the programmer to hard-code the display functions.

void CGetRowsDlg::DoGetRows()
{
   COleVariant      cRows;
   COleVariant      varField;
   CString         strLBRow;
   TCHAR            szId[16];
   LONG            lNumRecords;
   HRESULT         hResult;
   LONG            lIndex[2];
   CListBox         *pListBox = (CListBox *)GetDlgItem(IDD_GETROWSLIST);

   // Perform GetRows on Employee table. Retrieve MAX_EMP_REC rows and
   // store results as a variant in cRows.
   cRows = m_cEmpRecordSet.GetRows(MAX_EMP_REC);

   // Find out how many records were actually retrieved.
   // Note that lNumRecords is 1 based
   SafeArrayGetUBound(cRows.parray, 2, &lNumRecords);

   // Clear the listbox for displaying the row values.
   pListBox->ResetContent();

   //Step through the returned rows.
   for (lIndex[1] = 0; lIndex[1] <= lNumRecords; lIndex[1]++)
      {
      // Clear the string containing the row values.
      strLBRow.Empty();

      // Set array index to EmpID field.
      lIndex[0] = EMP_EMPLOYEE_ID;

      // Use OLE safe array function to access fields.
      SafeArrayGetElement(cRows.parray, &lIndex[0], &varField);

      // EmpID is known to be a long integer value. Store the value in
      // a string. The type check is used because the array may
      // contain empty rows.
      if(varField.vt == VT_I4)
         {
         wsprintf(szId, "%d,  ", varField.iVal);
         }
      else      // empty row
         {
         strcpy(szId, _T("Unexpected data type"));
         }

      strLBRow += (LPCTSTR)szId;

      // Set array index to LastName field.
      lIndex[0] = EMP_LAST_NAME;

      // Use OLE safe array function to access fields.
      SafeArrayGetElement(cRows.parray, &lIndex[0], &varField);

      // Add LastName to the row string.
      strLBRow += (LPCTSTR)varField.bstrVal;

      // Display string.
      pListBox->AddString(strLBRow);
      }
}

Using the dbDAO GetRowsEx Method

The GetRowsEx method retrieves multiple rows and allows you to specify the data types of the fields stored in your application variables. It has the following parameters:

Parameter | Data Type | Description
pvBuffer | LPVOID | Pointer to buffer in which to store returned rows
cbRow | LONG | Length of row in bytes
prb | LPDAORSETBINDING | Pointer to binding structure (see below)
cBinding | LONG | Number of bindings
pvVarBuffer | LPVOID | Pointer to buffer in which to store variable-length data
cbVarBuffer | LONG | Length in bytes of pvVarBuffer
lRows | LONG | Number of rows requested

The DAORSETBINDING structure specifies how data is to be copied from the rows to the memory buffer. A separate binding structure must be filled in for each field retrieved. DAORSETBINDING is defined as follows:

typedef struct
   {
   DWORD dwBindIndexType;
   union
      {
      LONG  i;
      LPCTSTR pstr;
      };
   DWORD dwType;
   DWORD dwOffset;
   DWORD cb;
   } DAORSETBINDING, *LPDAORSETBINDING;

Member | Description
dwBindIndexType | Specifies whether field is indicated by an index number or by name (use one of the values specified in Settings)
dwType | Specifies the data type (use one of the values specified in Settings)
dwOffset | Offset in bytes in the row buffer where data is copied
cb | Field length in bytes

Settings

You can use one of the following values for BindIndexType.

Constant | Description
dbBindIndexINT | index
dbBindIndexSTR | name

You can use one of the following values for Type.

Constant | Datatype
dbBindI2 | short
dbBindI4 | long
dbBindR4 | float
dbBindR8 | double
dbBindCY | currency
dbBindDATE | DATE
dbBindBOOL | VARIANT_BOOL
dbBindUI1 | unsigned char
dbBindVARIANT | VARIANT
dbBindWCHAR | wchar_t[]
dbBindSTRING | (same as dbBindWCHAR for Unicode, dbBindUI1for ANSI)
dbBindLPSTR | char_pointer
dbBindLPTSTR | wchar_pointer
dbBindLPSTRING | (dbBindLPTSTR for Unicode, dbBindLPSTR for ANSI)
dbBindBookmark | CdbBookmark
dbBindBlob | unsigned char pointer

The following code from the GetRows sample shows how to use GetRowsEx. Note that the table schema is known a priori, allowing you to predefine a structure for the data.

Two different binding schemes for retrieving string data are shown. If the size of the strings is fixed, then you can retrieve them directly into the structure. If you are using variable length strings, they will be placed sequentially in a single large buffer and a pointer into that buffer will be stored in the struct.

// User-defined structure for storing data returned by GetRowsEx.
typedef struct
// Structure for GetRowsEx
typedef struct
   {         // employee id as a long
   LONG   lEmpId;
            // pointer into pVarBuffer to LastName
   TCHAR   *strLastName;
            // the first name (\0 terminated)
   TCHAR   strFirstName[20];
   } EMP, *LPEMP ;

/* Employee table binding. This structure can be kept    in a header file and modified as needed (for    example, when you update the table definition).    Filling in the structure statically allows you to    define bindings once, rather than each time you    read data.
*/
DAORSETBINDING   Bindings[] =
{
//Index Type      Column      Type         Offset            Size
{dbBindIndexINT,   EMP_ID,      dbBindI4,      offsetof(EMP,lEmpId),      sizeof(LONG)},
{dbBindIndexINT,   EMP_LNAME,   dbBindLPSTRING,   offsetof(EMP,strLastName),   sizeof(TCHAR *)},
{dbBindIndexINT,   EMP_FNAME,   dbBindSTRING,   offsetof(EMP,strFirstName),   sizeof(TCHAR) * 20}
};

// Perform dbDAO GetRowsEx against the Employee table
void CGetRowsDlg::DoGetRowsEx()
{
   LPEMP         pEmpRows = new EMP[MAX_EMP_REC];
   CListBox      *pListBox = (CListBox *)GetDlgItem(IDD_GETROWSLISTEX);
   CString         strLBRow;
   TCHAR         szId[16];
   LONG         lNumRecords;
   LONG         lCount;
   TCHAR         pBuf[MAX_EMP_REC * 15];   // allow average of 15 chars/name

   // Call GetRowsEx to fetch rows.
   lNumRecords = m_cEmpRecordSet.GetRowsEx(
         pEmpRows,         // Pointer to data buffer.
         sizeof(EMPS),      // Length of row in bytes.
         &Bindings[0],      // Pointer to binding structures.
         sizeof(Bindings) / sizeof(DAORSETBINDING),   // Number of bindings.
          pBuf,            // Storage for variable-length data (lastname).
          sizeof(pBuf),   // Bytes available for variable-length data.
         MAX_EMP_REC);      // Get MAX_EMP_REC rows.

   //Step through the returned rows and display results.
   for (lCount = 0; lCount < lNumRecords; lCount++)
      {
      strLBRow.Empty();      // Clear the string containing the row values.
      wsprintf(szId, _T("%d,  "), pEmpRows[lCount].lEmpId);
      strLBRow += szId;
      strLBRow += pEmpRows[lCount].strLastName;
      strLBRow += _T(", ");
      strLBRow += (LPCTSTR) pEmpRows[lCount].strFirstName;
      pListBox->AddString(strLBRow);
      }

   delete [] pEmpRows;         // Free memory.
}


Getting Started with dbDAO

Here are the steps you need to take to get started putting together a project using dbDAO.

To put together a project using dbDAO

  1. Include the two header files dbdao.h and dbdaoerr.h.

  2. Define the following constants:

    For ANSI projects

    #define OLE2ANSI

    For Unicode projects

    #define UNICODE
#define _UNICODE
  3. Include the following LIB file in your project library:
    ddao35.lib

Note Be sure to use the corresponding dbDAO file for a particular type of build. Each build is a combination of ANSI or Unicode, debug or release, and shared or static DLLs. If you do an ANSI, debug, shared DLL build, use the ANSI, debug, shared DLL dbDAO file (Debug\Ddao35d.dll). This is because the dbDAO classes rely on Microsoft Foundation Classes (MFC) classes internally, and mixing versions of MFC classes can produce unexpected results.


Other dbDAO DLL Versions

Other versions of the dbDAO DLL may be built that vary with respect to the following capabilities:

  • Use of ANSI or Unicode strings.

  • Built-in debugging functionality.

  • Use of shared or static Microsoft Foundation Classes (MFC) DLLs.

The MakeFile that is installed with the DAO SDK (Dbdao.mak) provides you with four pre-built dbDAO DLLs, and subprojects to build them, plus four others. The four pre-built DLLs are:

  • Release\Ddao35.dll (dbDAO – Win32 Release) — This is the ANSI version of the dbDAO classes. It dynamically links with the MFC DLL, making Ddao35.dll smaller and allowing it to share the MFC DLLs on a user's system with other applications that also use MFC 4.2 or later. Developers writing applications with this DLL must ensure that their setup program distributes the MFC DLLs. The DAO SDK Setup program installs this file into your system directory.

  • Releaseu\Ddao35u.dll (dbDAO – Win32 Release Unicode) — This is the Unicode version of the dbDAO classes. It is otherwise identical to Ddao35.dll. The DAO SDK Setup program installs this file into your system directory.

  • Debug\Ddao35d.dll (dbDAO – Win32 Debug) — This is the debug ANSI version of Ddao35.dll. It is intended for developers who have to debug into the dbDAO source code. Developers should not ship this version, as it is slower and has debug functionality that users will not want.

  • Debugu\Ddao35ud.dll (dbDAO – Win32 Debug Unicode) — This is the debug Unicode version of Ddao35u.dll. It is intended for developers who have to debug into the dbDAO source code. Developers should not ship this version, as it is slower and has debug functionality that users will not want.

The other four subprojects defined in the dbDAO MakeFile are:

  • Releases\Ddao35.dll (dbDAO – Win32 Release Static MFC) — This file is for ANSI applications that are statically linked to the MFC library. It has the MFC class library built into it.

  • Releaseus\Ddao35u.dll (dbDAO – Win32 Release Unicode Static MFC) — This file is for Unicode applications that are statically linked to the MFC library. It has the MFC library built into it.

  • Debugs\Ddao35d.dll (dbDAO – Win32 Debug Static MFC) — This is the debug version for ANSI applications that are statically linked to the MFC library. Developers should not ship this version, as it is slower and has debug functionality that users will not want.

  • Debugus\Ddao35ud.dll (dbDAO – Win32 Debug Unicode Static MFC) — This is the debug version for Unicode applications that are statically linked to the MFC library. Developers should not ship this version, as it is slower and has debug functionality that users will not want.


Error Handling

The dbDAO classes use exception handling to let the developer know when an error has occurred. The CdbException class provides minimal exception handling (it only has an HRESULT member); the CdbLastOLEError and CdbError classes offer more detailed error handling.

To catch an exception for dbDAO, use the CdbException class in your catch statement:

try
   {
   // Some dbDAO function calls
   }
catch (CdbException e)
   {
   // Handle the exception
   }

In many cases, you'll just want your exception handling code to examine the HRESULT returned. In that case, the only thing you need is the CdbException object. The only member of CdbException is m_hr, the HRESULT. Error constants that can be returned by dbDAO member functions are defined in Dbdaoerr.h. To determine exactly what the error was, you can compare the HRESULT in CdbException with values defined in Dbdaoerr.h. For example:

#include <dbdao.h>
#include <dbdaoerr.h>

void OpenADatabase(CString stDBName)
   {
   CdbDBEngine dben;
   CdbDatabase db;

   try
      {
      db = dben.OpenDatabase(stDBName);
      }
   catch (CdbException e)
      {
      assert (e.m_hr == E_DAO_FileNotFound);
      // Inform the user that the file specified doesn't exist
      // E_DAO_FileNotFound is a constant defined in dbdaoerr.h.
      }
   }

DAO returns numeric error values in two forms. One is in the form of an HRESULT. This is the form familiar to OLE programmers. The other is in the form of an IDA which is the form more familiar to Visual Basic programmers who have worked with DAO. To read the HRESULT, examine the m_hr member of the CdbException object. To read the error as an IDA value, wrap the m_hr member of CdbException in a DBERR macro (defined in dbdao.h).

For more involved error handling, you may want to use the CdbError class. The CdbError class is associated with the CdbDBEngine object's CdbErrors collection. It holds the last DAO errors which have occurred. The CdbErrors collection may hold more than one error if there is more information that can be passed. For example, an ODBC error usually results in more than one error in this collection. The members of this class contain:

  • The number value associated with the error.

  • The DAO description for that error.

  • The object on which the error occurred (in the form DAO.object; for example, DAO.Database).

  • The DAO Help file and Help context for obtaining more information about the error.

The number value stored in the CdbError object is in the form of an IDA rather than an HRESULT, as in the CdbException object. For example:

void OpenADatabase(CString stDBName)
   {
   CdbDBEngine dben;
   CdbDatabase db;

   try
      {
      db = dben.OpenDatabase(stDBName);
      }
   catch (CdbException e)
      {
      int iError, cError;
      CString stError = _T("");

      cError = dben.Errors.GetCount();
      for (iError = 0; iError < cError; iError++)
         {
         stError +=
         dben.Errors[iError].GetDescription();
         stError +=
         dben.Errors[iError].GetNumber();
         stError += _T("\n");
         }
      //Inform the user of the error with stError.
      }
   }

Also used for more detailed error handling, the CdbLastOLEError class is more generic to OLE than to DAO. It allows you to get extended error information on the last OLE error to occur, including its description. Regardless of whether the last error to occur was a DAO or an OLE error, you can use this class to determine the error. For example:

void OpenADatabase(CString stDBName)
   {
   CdbDBEngine dben;
   CdbDatabase db;

   try
      {
      db = dben.OpenDatabase(stDBName);
      }
   catch (CdbException e)
      {
      CdbLastOLEError ex;
      CString stError;

      stError.Format("0x%lx : %s", e.m_hr,
            (LPCTSTR)ex.GetDescription());
      //Inform the user of the error with stError.
      }
   }


How to Build the DAO Method Samples

The DAO method samples are provided as source files in the directory Samples\dbdao InstallDirectory\DAOSDK\SAMPLESon the MSDN Library disc. You can copy, compile, and execute them in a Microsoft Visual C++ project. The method samples are the Microsoft Visual C++ equivalents of the Microsoft Visual Basic DAO method samples. In order to correspond as closely as possible to the Visual Basic samples, the Microsoft Visual C++ method samples are designed as ANSI console applications.

Examples should be simple, so common functions as defined in stdio.h are used whenever possible. When necessary, less common routines as defined in conio.h are used. DAO depends on the COleVariant and CString Microsoft Foundation Classes (MFC), and objects from these classes are used often in the samples.

The procedures for creating samples are listed below. In order to build the samples, create a dummy project in Microsoft Visual C++, and a dummy source file within that project. When you want to test a sample, copy and paste it into the dummy source file then build the project.

We suggest naming the project avatar.mdp, and the source file, avatar.cpp. (An "avatar" is the embodiment of something else. Avatar.cpp will embody each sample. Using it will conserve disk space and minimize compilation time.). This procedure assumes everything listed below is done in one session.

To create the Avatar workspace

  1. Start Microsoft Visual C++.

  2. From the File menu; select New.

  3. From New, select Project Workspace.

  4. Select Console Application.

  5. Type in a name for the project. (These examples suggest the name “avatar”.)

  6. Select Create.

To create the Avatar source file

  1. Start Microsoft Visual C++.

  2. From the File menu, select New.

  3. Select Text File from the menu and choose Save.

  4. Name the file avatar.cpp when prompted to do so and close the text file.

To configure the Avatar project, you must select the project, then specify the Tools and Build settings, and save the project.

To configure Avatar project

  1. Select the Avatar project.

  2. Choose Save.

To specify the Tools settings

  1. From the Tools menu, select the Options menu item.

  2. Choose the Directories tab.

  3. From the Show Directories For menu on the Directories tab, select Include Files.

  4. Add the DAOSDK\Include directory.

  5. On the Show Directories For: menu on the Directories tab, select Library Files.

  6. Add the DAOSDK\Lib and DAOSDK\Lib\Debug directories.

To specify the Build settings

  1. From the main Build menu, choose Settings.

  2. Select the General tab.

  3. Select the Microsoft Foundation Classes list.

  4. Select Use MFC in a Shared DLL.

  5. Select the C/C++ tab.

  6. From the Category list, select Code Generation.

  7. From the Use Run Time Library list, select the Debug Multi-threaded DLL item.

When you have finished configuring the Avatar project, you must close the Workspace.

To close the Workspace

  1. From the File menu, select Close Workspace.

  2. From the File menu, select Exit.

To Select the Library Modules

  1. Select the Link tab.

  2. On the Category menu, select General.

  3. In the Object/Library Modules text box, add ddao35d.lib. (This is the ANSI Debug module.

    Note Other choices are ddao35.lib (ANSI Release), ddao35ud.lib (Unicode Debug), and ddao35u.lib (Unicode Release).

If you cannot debug trace into dbDAO libraries, you may need to copy the debug version of the .dll or .pdb files into your Windows\System (for Win95) or Windows\System32 (for Windows NT) directory.

To rebuild the sample

  1. Copy a sample file into avatar.cpp.

  2. Build and execute the project. The word Execution will display in an MS-DOS Prompt window.


ANSI and Unicode Strings

All 16-bit applications use ANSI strings. 32-bit applications may use either ANSI or Unicode strings. ANSI applications store strings as unsigned char, each byte containing a different character. Unicode applications store strings as unsigned short, each short integer value containing a different character.

To specify ANSI, declare the following in your project settings:

#define OLE2ANSI

To specify Unicode, declare the following in your project settings:

#define _UNICODE

The advantage of using Unicode in your applications is that it enables you to easily localize your application into languages such as Chinese, where two bytes are required to store characters. ANSI applications require special DBCS (Double Byte Character Set) functions in order to be localized into languages such as Chinese.

The advantage of using ANSI strings is that, in Microsoft Windows 95, the Windows system calls take ANSI strings; therefore, you must convert Unicode strings to ANSI before calling into these functions.

You can compile your application in ANSI or Unicode by using the _T() macro. _T is defined by Microsoft Visual C++ and is used to wrap all string literals. In ANSI, this macro is a no-op. In Unicode, it appends the L keyword to inform the compiler that the literal is to be read in as Unicode. For example:

void OpenADatabase()
   {
   CdbDBEngine dben;
   CdbDatabase db;

   db = dben.OpenDatabase(_T("MyDB.MDB"));
   }

The above code will compile for both ANSI and Unicode applications.


Converting Method Samples to Unicode

The DAO method samples are designed to illustrate the DAO methods in a simple, yet effective manner. Thus, the samples are written as ANSI console applications because they are the easiest type of application to read and require the least prior knowledge to understand.

The samples should also work as Unicode console applications, but they will require modification.

Note The samples are already partially modified for your convenience. But why is there any support at all for Unicode when the samples are designed for ANSI builds? Frankly, to encourage you to write your future applications so they will be able to handle ANSI or Unicode.

To convert the method samples to Unicode

  1. Convert literal strings to Unicode. All literal text strings should be enclosed in the _T( string ) macro. In an ANSI build, this macro has no effect on string. In a Unicode build, string is prefixed with 'L' which declares it to be Unicode.

  2. Change declarations of char to TCHAR. In an ANSI build, TCHAR is defined to be char; in a Unicode build, it is defined to be wchar_t.

  3. Change printf functions to _tprintf. In an ANSI build, _tprintf is defined to be printf; in a Unicode build, it is define to be wprintf. In an ANSI build, the printf formatting argument for an ANSI string is "%s", and the argument for a Unicode string is "%S". In a Unicode build, this rule is reversed: ANSI strings are formatted with "%S" and Unicode strings are formatted with "%s". Adjust formatting arguments accordingly.

  4. Change _cgets, sscanf, and associated logic to use swscanf, and/or getws.

These samples are the Microsoft Visual C++ equivalents of the Visual Basic DAO samples, so it was necessary to map Microsoft Visual Basic functionality to equivalent Microsoft Visual C++ constructs. However, certain constructs in the ANSI build (such as _cgets) have no Unicode equivalent. In this case you must change the program logic to get the desired result.


Helpful MFC Classes Used in DAO

DAO makes extensive use the COleVariant, CString, and COleDate Time Microsoft Foundation Classes (MFC). Objects from these classes are passed to and from many DAO methods and properties. These classes also provide helpful methods for data comparison and manipulation that make developing applications easier. Some methods of the COleVariant and CString classes are listed below.

When debugging applications involving COleVariants, it's helpful to have a way to convert the variant to a displayable string. One way to do this is to use the CString::Format method. For example:

   COleVariant   vVal(1000, VT_I4);
   CString      strVal;
   //
   strVal.Format("Value = %ld\n", vVal.lVal);

Another way is to use the COleVariant::ChangeType method to convert the variant to a BSTR string. The variant itself can be converted, or another variant can be used as the source of the data. The string that results is always Unicode, unless the variant was created with the VT_BSTRT variant type. For example:

   COleVariant   vVal(1000, VT_I4),
               vUni(_T("unicode")),
               vAnsi(_T("ansi"), VT_BSTRT);
   //
   vVal.ChangeType(VT_BSTR);    // Convert to L"1000".
   vUni.ChangeCode(VT_BSTR);  // No change.
   vAnsi.ChangeType(VT_BSTR); // Also, no change.

Note By default, the COleVariant string constructor creates a variant with a Unicode value and a VT_BSTR variant type. In non-Unicode builds, DAO methods like SetField, Seek, etc., require variants with an ANSI string value. ANSI strings are constructed when you specify the optional variant type, VT_BSTRT. However, the resulting variant is still marked with the VT_BSTR variant type.

The COleVariant::ChangeType method will not convert a BSTR variant to Unicode, even if its value is really an ANSI string. When displaying the string you should be careful to use appropriate Unicode or ANSI formatting, or a function like wcstombs, which converts a Unicode string to multi-character.

Another debugging tool for formatting variants is the CCrack class. This is not a standard MFC class, but a part of the DAOVIEW sample distributed with Microsoft Visual C++. It uses the CString class to either format the value of a variant as a displayable string, or create a string describing the variant type. You can adapt this class to your purposes as needed.

COleVariant

Construction | Description
COleVariant | Constructs a COleVariant object from several data types, including short, long, null-terminated string, CString, Boolean, variant, date/time, double, and float.

Method | Description
Attach | Attaches a VARIANT to a COleVariant.
ChangeType | Changes the variant type of this COleVariant object.

Operators | Description
operator LPCVARIANT | Converts a COleVariant value into an LPCVARIANT.
operator LPVARIANT | Converts a COleVariant object into an LPVARIANT.
operator = | Copies a COleVariant value.
operator == | Compares two COleVariant values.

CString

Construction | Description
CString | Constructs CString objects from CStrings, null-terminated single-byte and wide-byte strings.

Method | Description
GetLength | Returns the number of characters in a CString object.
IsEmpty | Tests whether a CString object contains no characters.
Empty | Forces a string to have 0 length.
Compare | Compares two strings (case sensitive).
CompareNoCase | Compares two strings (case insensitive).
Format | Format the string as sprintf does.

Operator | Description
operator = | Assigns a new value to a CString object.
operator + | Concatenates two strings and returns a new string.
operator += | Concatenates a new string to the end of an existing string.
operator == <, etc. | Comparison operators (case sensitive).
operator LPCTSTR | Directly accesses characters stored in a CString object as a C-style string.
operator [] | Returns the character at a given position — operator substitution for GetAt.


Converting Applications to ODBCDirect

The following are tips for converting existing applications that run against Microsoft Jet databases to ODBC data sources. They assume the database has already been placed on the server and that you will only want to use ODBCDirect to access your data. In the meantime, the tips listed below will quickly get you up and running with ODBCDirect.

  • Change the Workspace Type — If you do not create any workspaces, you still need to tell DAO what the default workspace type should be ODBCDirect. This is accomplished by setting the DefaultType property of DBEngine to dbUseODBC before doing any operations that need the default workspace. Once a workspace is created, you cannot change its type.

  • If you explicitly create workspaces in your application while DefaultType is set to dbUseODBC, then all new workspaces will be ODBCDirect workspaces. However, if you want your code to be self-documenting, or if you will be using both Microsoft Jet and ODBCDirect workspaces, you can pass a fourth parameter to the CreateWorkspace method, specifying the type of workspace to create.

  • Change OpenDatabase — You will need to change the arguments passed to OpenDatabase. Instead of passing a database name in the first parameter, you will now pass a connection string in the fourth parameter. (Note that all connection strings start with "ODBC;".)

  • You may decide to open connections instead of databases. In this case, change your OpenDatabase calls to OpenConnection. Both functions take similar arguments.

  • Handling Data Definition Language (DDL) — DAO’s ODBCDirect functionality does not support the TableDefs or Indexes collections. This means your application will no longer work if it creates new TableDefs or uses the Indexes collection of a TableDef.

  • If this is a problem there are two ways you can change your code: You can create a Microsoft Jet workspace and open a second database to the data source, doing all DDL work within it. Or you can execute SQL calls to create and find objects. SQL calls are best if you want to keep from loading Microsoft Jet. Creating a second database works well if you want to limit the amount of code that changes.

  • Creating/Using QueryDef objects — In ODBCDirect workspaces the Database object does not support the CreateQueryDef method. That is handled by the Connection object. In your code, you need to change all CreateQueryDef calls to be executed on the Connection property of the Database rather than the Database object itself, or change all OpenDatabase to OpenConnection. QueryDef objects created in ODBCDirect are not stored in the database and are lost when the object is closed or goes out of scope.

  • Opening Recordset objects — ODBCDirect Recordset objects default to the fastest Recordset type rather than the most functional, as in Microsoft Jet. Typically this is a Recordset that cannot scroll backwards and is read only. If you need more functionality in the Recordset, you may specify that explicitly. If you need to scroll backwards or need bookmarks, then choose a different Recordset type, such as dbOpenDynaset. If you need to update the Recordset, choose a locking type, such as dbOptimistic.

  • Code written in a Microsoft Jet workspace that plans on editing data and opens a Recordset with only the name argument provided will not run in ODBCDirect. However, you can change the OpenRecordset to supply a Recordset type and locking constant that will allow updating.

  • Parameterized queries — ODBCDirect does not support named parameters. The syntax for a parameter in an SQL statement is a ‘?’, rather than a name as in Microsoft Jet. For example, the Microsoft Jet SQL "SELECT * FROM Employees WHERE LastName = txtName" creates a parameter called “txtName.” In ODBCDirect, the SQL would read "SELECT * FROM Employees WHERE LastName = ?". In the Parameters collection, the name of the parameter would be "Parameter1". It should be noted that Microsoft Jet allows you to say "Parameters iAuthId Integer; SELECT * from authors where au_id = iAuthId". Since ODBCDirect does not have named parameters, you cannot use the "Parameters …;" part of the previous example.

  • Review program for optimizations — Always go back over the program and look for optimizations because ODBCDirect offers new and different ways to improve performance.


Using dbDAO in a DLL

Although many people use DAO from an executable, you may want to create DLLs for distribution so that others can use them in their applications. If so, then you are responsible for starting DAO from inside the DLL. Various restrictions on DLLs prevent this from being done automatically while the DLL loads, and the dbDAO classes will not handle it for you. Instead, you must explicitly force the load.

For example, the following code works fine inside an EXE, but the same code does not work as a DLL:

class CMyObj
   {
public:
   CMyObj();
    ~CMyObj();
private:
   CdbDBEngine      m_cDBEng;
   };

CMyObj::CMyObj()
 {
 }

CMyObj::~CMyObj()
   {
   delete m_cDBEng;
   }

// globally instantiated object - the cause of the DLL problem
CMyObj myObj;

#ifdef MAKE_AS_DLL
// exported function that is called by some console app
// this case hangs
__declspec(dllexport) void hello()
   {
   }

#else
// when this is built as a console app, it works fine
void main()
 {
 return;
 }
#endif // MAKE_AS_DLL

The line causing the problem is the declaration:

   CMyObj myObj;

When the DLL is loaded and the class is instantiated, an attempt is made to start DAO. To work around this problem, you must create an entry point in your routine that explicitly creates DAO, and have your DLL users call that entry point. You could do this as part of other initialization, for example. In other words, if you declare the global variable as a pointer to CdbDBEngine, then construct the class in your initialization function.


Using DAO Interfaces

DAO acquires functionality through DAO Component Object Model (COM) interfaces. DAO simplifies managing COM interfaces by incorporating them into dbDAO classes such as CdbRecordset, CdbWorkspace, etc.

Incorporating an interface into a DAO object makes the interface unavailable to the programmer, but sometimes access to the interface is required. For example, using DAO in a multi-threaded apartment-model application requires access to the interface so it can be marshaled across apartments (see DAO and the Apartment-threading Model).

Normally, acquiring an interface would require you to call CoCreateInstance() with the appropriate class and interface identifiers, then manage the returned interface pointer. However, DAO has already acquired these interfaces for its own operation and offers them to you through the GetInterface() method and the LPUNKNOWN operator.

GetInterface and LPUNKNOWN are members of every DAO class. The LPUNKOWN operator looks like a type cast, and internally calls the GetInterface() method.

Syntax

LPUNKNOWNGetInterface(BOOL bAddRef = FALSE,

BOOL bThrowException = TRUE) const;

operator LPUNKNOWN(){ return GetInterface();}

Type | Example | Description
BOOL | bAddRef = FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.
BOOL | bThrowException = TRUE | Optional. A Boolean. If TRUE, an error is thrown if an interface is not set in the target object.

Usage

#include <dbdao.h>
#include <dbdaoerr.h>
CdbDBEngine   engine;         // Declare a DAO object
DAODBEngine   *pIdben;         // Declare a DAO interface pointer
// Construct four DAO objects. Increment AddRef.
/* 1 */
// Use GetInterface to AddRef. Explicitly Release when // done.
pIdben = (DAODBEngine   *)engine.GetInterface(TRUE);
...
pIdben->Release();
/* 2 */
// Use DAO to AddRef and Release.
CdbDBEngine Engine2(engine.GetInterface(), TRUE);
Engine2.GetVersion();
/* 3 */
CdbDBEngine Engine3((LPUNKNOWN) engine, TRUE);
Engine2.GetVersion();
/* 4 */
CdbDBEngine *pEngine4 = new CdbDBEngine(pIdben, TRUE);
pEngine4->GetVersion();

Remarks

See DAO and the Apartment-threading Model for an extended example. See the "DAO OLE Automation Interfaces" section of "Using Microsoft Visual C++ and DAO" for additional remarks on DAO interfaces.


DAO and the Apartment-threading Model

DAO 3.5 can be used in several threads of a multi-tasking application to accomplish many tasks simultaneously. For example, a long running query may be performed by one thread, while the contents of a large recordset may be displayed by another thread.

This is possible because DAO 3.5 is an inproc (DLL-based) server which supports the OLE Apartment-threading Model. The Apartment-threading Model defines one way interface calls are made to an OLE object and how interface pointers are passed between threads.

Characteristics of the Apartment-threading Model

The Apartment-threading Model is characterized by these attributes:

  • One or more threads in a process uses OLE and calls to OLE objects are synchronized by OLE. Thus, several clients may call DAO simultaneously because OLE will deliver the calls in order and one at a time.

  • An apartment is a set of OLE objects associated with a particular thread. These objects are created by the thread or are proxies created as a consequence of marshaling to the thread. If the object or proxy needs to be accessed by another apartment, its interface pointer must be marshaled to that apartment where a new proxy is created.

  • The client thread associated with an apartment must call CoInitialize() or CoInitializeEx(NULL, COINIT_APARTMENTTHREADED).

  • The client thread associated with an apartment must retrieve and dispatch window messages so the associated objects can receive incoming calls.

Client Responsibilities in the Apartment-threading Model

The client responsibilities in the Apartment-threading Model are listed below:

  • Marshaling — A client that uses the apartment model must marshal interfaces of an object between apartments by using CoMarshalInterThreadInterfaceInStream and CoGetInterfaceAndReleaseStream.

  • For example, if Apartment 1 in the client has an interface pointer, and Apartment 2 requires use of it, Apartment 1 must marshal the interface using CoMarshalInterThreadInterfaceInStream. The stream returned by this function is thread-safe and must be stored in a variable accessible by Apartment 2. Apartment 2 must pass this stream to CoGetInterfaceAndReleaseStream to unmarshal the interface and get back a pointer to a proxy through which it can access the interface.

  • CoInitialize/CoInitializeEx — The thread of an apartment must initialize OLE for its use by calling CoInitialize or CoInitializeEx(NULL, COINIT_APARTMENTTHREADED). This thread must remain alive until the client has completed all OLE work.

  • Dispatching Messages — OLE uses window messages to synchronize the delivery of calls to an object. The thread of an apartment must use a loop containing calls to PeekMessage, TranslateMessage, and DispatchMessage to retrieve and dispatch window messages. In the example above, Apartment 1 implements this loop.

Only Unicode Interfaces can be Marshaled

The DAO 3.5 SDK includes several versions of its DLLs. However, DAO only supports the Unicode interfaces for multi-threading. This is because DAO relies on OLE to do marshaling and OLE is based on Unicode. This also means that because Microsoft Windows 95 does not fully support Unicode, DAO can not be used in multiple threads on Windows 95.

In the example below, the DAO 3.5 client creates a shared DBEngine in one thread, and then marshals the DBEngine interface to another thread that accesses the DBEngine. The interface is acquired with the GetInterface DAO method (see "Using DAO Interfaces").

(Error handling excluded for readability):

UINT TestThread(LPVOID);
LPSTREAM pstmDBEngine;

UINT TestThread(LPVOID pParam)
{
CdbDBEngine *pengine;
DAODBEngine *pIdben;
   TRACE("Hello");

   CoInitialize();
   CoGetInterfaceAndReleaseStream( pstmDBEngine,
            IID_DAODBEngine, (void **) &pIdben);
   pengine = new CdbDBEngine(pIdben, TRUE);
   pengine->GetVersion();   // Now you can use DAO.
   delete pengine;
   TRACE("Goodbye");
   return 0;
}

void CEnginetestDlg::OnOK()
{
CdbDBEngine   engine;
DAODBEngine   *pIdben;
CWinThread    *pThread;
MSG          msg;

pIdben = engine.GetInterface();
pThread = AfxBeginThread(TestThread, this,
               THREAD_PRIORITY_NORMAL,
               0, CREATE_SUSPENDED);
CoMarshallInterThreadInterfaceInStream(
               IID_IDAODBEngine, pIdben,
               &pstmDBEngine);
pThread->ResumeThread();

// Now, go into a message loop. This is a requirement // for apartment-model threading.
for (;;)
   {
   if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
      {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
      }
   }
}


DAO SDK Files

Microsoft Visual C++ 5.0 includes the DAO SDK. The dbDAO classes do not work with earlier versions of Microsoft Visual C++. In addition, the only supported form of DAO from Microsoft Visual C++ is a 32-bit in-process DLL requiring either Microsoft Windows 95 or Windows NT; it does not work with Win32s.

Running the DAO SDK Setup program does everything required to start programming with dbDAO, including copying all necessary DLLs, updating the registry, and setting up a directory structure for the headers, libraries, and sample programs.

The following tables describe the files that are installed by DAO SDK Setup including:

  • INCLUDE Files

  • SRC Files

  • LIB Files

  • DLL Files

  • SAMPLES Files

  • SETUP Files

INCLUDE Files

Note To start building a dbDAO application you only need the first two header files listed below — dbdao.h and dbdaoerr.h.

File | Description
dbdao.h | Provides all dbDAO class definitions and helper macros, and includes other necessary header files. dbdao.h must be included by all applications that use dbDAO.
dbdaoerr.h | Defines all the errors that can be returned by DAO. See Error Handling for more information on how to handle errors in dbDAO.
daogetrw.h | Required by applications that use GetRowsEx. It defines HRESULTs not included in dbdaoerr.h, binding constants for the function and the DAOCOLUMNBINDING structure. daogetrw.h does not need to be included in programs that use dbDAO; it is provided so you can rebuild dbdao.cpp. For more information about using GetRowsEx, see Performing Bulk Fetches with GetRows and GetRowsEx.
_dbdao.h | The _dbdao.h file is used in the compilation of dbdao.cpp. It contains needed definitions and helper macros for the dbDAO source files. _dbdao.h does not have to be included in programs that use dbDAO; it is provided so you can rebuild dbdao.cpp.
dbdaoint.h | Defines the underlying DAO OLE Automation (OA) interfaces, their methods, parameters, and so on. Use this file to program directly to the DAO OA interfaces. It is included by dbdao.h.
dbdaoid.h | Defines the interface IDs for the underlying DAO OA objects. It is included by dbdao.h.

SRC Files

File | Description
dbdao.cpp | Source code for the dbDAO class libraries. This code creates a set of C++ classes that “cover” the OLE Automation interfaces that DAO exposes. A compiled version of this code is provided in ddao35.dll, which is installed in your system directory. The source code is provided to simplify debugging and building other versions of the dbDAO DLL. See “Other dbDAO DLL Versions” for information on the other versions you can build.
dbdaouid.cpp | Source code for ddaouid.lib.
dbdao.mak | MakeFile for dbDAO class libraries. See “Other dbDAO DLL Versions” for information on the other versions you can build.
dbdao.rc | Generated resource file.
stdafx.h | Standard MFC header file.

LIB Files

NoteThe DAOSDK 3.5 libraries will not operate correctly if built with a version of Microsoft Foundation Classes older than 4.2.

File | Description
ddao35.lib | Import library for ddao35.dll.
ddao35u.lib | Import library for ddao35u.dll (Unicode version of ddao35.dll).
ddao35d.lib | Debug version of ddao35.lib.
ddao35ud.lib | Debug version of ddao35u.lib.
ddaouid.lib | Import library that defines the GUIDs for DAO.

DLL Files

File | Description
ddao35.dll | dbDAO API’s (ANSI version).
ddao35u.dll | dbDAO API’s (Unicode version).
ddao35d.dll | Debug version of ddao35.dll.
ddao35ud.dll | Debug version of ddao35u.dll.

SAMPLES Files

File | Description
Employee | Based on Employees table in EMPLOYEE.MDB. Allows viewing of data and simple edits.
Daoread | Demonstrates different methods for reading data and displays fetch time for each method.
GetRows | Demonstrates how to use the GetRows and GetRowsEx methods.
Security | Displays the user and group information from a SystemDB workgroup database.
Stores | Maintains a database of branch stores.
MultThrd | Demonstrates multi-threading support in DAO.
Addrbook | Implements an address book application using data stored on an Internet Server.

SETUP Files

File | Description
DAOMin.rul | Template InstallShield setup script.
Regadll | Directory with source files for rebuilding the provided setup support DLL.
DAOSetup.rtf | Detailed instructions on creating your own setup program.


Installing DAO on Another Machine

In order to run a DAO-enabled application on another machine, you must properly install DAO on that machine. You can install DAO using one of the following methods:

  • Copy the supplied installation program and use it directly.

  • Modify the supplied InstallShield scripts and build them into your own InstallShield-based setup.

  • Create your own setup using some other tool set. This is not recommended (see Note below).

Note Creating your own installation without using the supplied InstallShield scripts as a starting point is not recommended. An OLE Automation server like DAO can only exist in one place on a machine, so if your setup does not work correctly it will break other applications that use DAO (such as Microsoft Access, Microsoft Excel, Microsoft Visual Basic, or other DAO-enabled applications). If you need to start from scratch, see the file DAOSetup.rtf in the Setup subdirectory of your DAO SDK installation for more details.

Some interesting combinations of the above methods are also useful. For example, you can combine method 1 with 3 and create your own setup program that calls the supplied installation in ‘silent’ or ‘scripted’ modes. These are discussed more below.


Using the Supplied Install Program

As shipped with Microsoft Visual C++ 5.0, the DAO SDK is divided into four subdirectories labeled disk1 through disk5. This setup has been structured so that you can take the parts you need and use them directly with no recompilation required. In particular, two options are available for redistribution:

  • Install DAO runtime with all data file formats (for example, Xbase and Excel)

  • Install DAO runtime with Jet MDB support only (version 3.x)

To enable these options, you need to replace the Setup.iss and Setup.pkg files that are found in disk1. A set of alternate replacement files are provided in the disk1 directory called Daomin.iss/Pkg/Ins (note the third file in this case). The Daomin files will install DAO with the ability to read Microsoft Jet 3.x databases only. In addition to replacing the ISS and PKG files, you will need to make sure that the appropriate compressed files are also available.

Assembling the Files

The DAOMIN installation requires the following files:

  • Setup.pkg

  • Setup.iss

  • Setup.ins (all three renamed from Daomin.*)

  • Disk1.id

  • Setup.exe

  • Uninst.exe

  • _Setup.lib

  • _Setup.dll

  • Daocore.1

  • Daocore.2

If you are distributing over a network, CD-ROM, or some other media format large enough to put all of the files into one directory, then you can simply place all the files in one directory and invoke Setup from that location. If you are distributing on 1.44 MB floppies, then take care to group the files the same way that they are grouped in the \Daosdk\Disk directories on your distribution CD-ROM; for example, DISK2 should include Daocore.2 and Jetisam.z. You will also need to add the file Disk2.id to your second disk.

Note If you alter how the files are grouped across directories and/or disks, you must supply a new InstallShield packing list (.pkg) file. See the InstallShield documentation for details on how to do this.

Executing Setup

Neither of the options outlined above require any input from the user. Execute the DAO Setup program with the following command line:

setup -s

This will silently install DAO with no visual feedback, unless another disk is required. If you omit the -s flag, the DAO Setup introductory screen will be displayed until the user chooses Next, which will start copying files.

If you are invoking setup from another program, you can check the status of the install two ways.

The first way is to check the return code of the Setup.exe call. This will tell you whether Setup.exe successfully began the installation process. However, since the setup happens in the background, the call will actually return before the setup is complete.

A second, more robust technique is to invoke setup with the command line:

setup -s -f2c:\somefile.log

The -f2 option forces a log file to be written to the location specified. By examining the log file, your program can determine if the setup has completed successfully by searching for the string “ResultCode=0”.

Note InstallShield in silent mode must write a log file. If you omit the -f option, it will try to create a log file in the default directory which often is a read-only diskette.


Creating Your Own Install Program

In the SETUP directory of the DAO SDK you will find a setup template that can be combined into your own InstallShield-based installation program. The files are:

File | Description
Daomin.rul | Template InstallShield setup script
Rega.dll | Directory with source files for rebuilding the setup support DLL that has been provided
Daosetup.rtf | Detailed instructions on creating your own setup program from scratch

This script assumes that you are using the InstallShield program that comes with Microsoft Visual C++. InstallShield has a version that is sold separately which provides more functionality, including functions that remove the need for the support DLL (specifically, the ability to register DLLs that have a DLLRegisterServer entry point and to automatically uninstall them using DLLUnregisterServer).

Refer to the documentation that comes with InstallShield for how to use it. The tools that it comes with allow you to ‘unpack’ the compressed files that comprise the SDK and tailor the packaging for your own setup. This allows you to distribute support for certain specific file formats, for example, rather than the supplied “all or none” options.


Using Another Setup Tool

If you want to use another setup tool, or, for example, your setup is simple enough to do by copying files using a .bat file, you can use a combination of the above approaches to reduce the work required and still have a robust setup.

Note Creating your own installation without using the supplied InstallShield scripts as a starting point is not recommended. An OLE Automation server like DAO can only exist in one place on a machine, so if your setup does not work correctly it will break other applications that use DAO (such as Microsoft Access, Microsoft Excel, Visual Basic, or other DAO-enabled applications). If you need to start from scratch, see the file Daosetup.rtf in the Setup subdirectory of your DAO SDK installation for more details.

The easiest way to do this is to use the supplied install program to do either a minimal or full install of the run-time components. You can have this happen without anything being displayed to the user by using the silent option outlined above. This will also provide full uninstall capabilities that you trigger programmatically.

If you use the automatic setup, an entry will be written to the registry at the location:

HKEY_LOCAL_MACHINE\Windows\CurrentVersion\Uninstall\Data Access Objects (DAO)

Below this entry there will be a key named UninstallString that will have a value of something like:

C:\Windows\uninst.exe -f "C:\program files\common files\Microsoft Shared\DAO\DelsLog.1"

Your setup program may wish to modify this (for example, change the name to “DAO portion of My Application”). Alternatively, you might remove the key altogether and trigger the uninstall when your own application is uninstalled. However you decide to handle this, you should ensure that DAO is uninstalled using the command line found in the registry. This will handle the appropriate DLL reference counting, clean up the registry, and take care of other setup details.


Trouble Registering DAO

If you have trouble registering DAO, make sure you have Oleaut32.dll, version 2.20.4049 or later. This DLL is not shipped with DAO 3.5, but is included with Visual Basic 5.0, Visual C/C++ 5.0, and Microsoft Office97.


DAO Overview

DAO (Data Access Objects) enables you to use a programming language to access and manipulate data in local or remote databases, and to manage databases, their objects, and their structure.


Object Models

DAO supports two different database environments or workspaces.

  • Microsoft Jet workspaces allow you to access data in Microsoft Jet databases, Microsoft Jet-connected ODBC databases, and installable ISAM data sources in other formats, such as Paradox or Lotus 1-2-3.

  • ODBCDirect workspaces allow you to access database servers through ODBC, without loading the Microsoft Jet database engine.

Use the Microsoft Jet workspace when you open a Microsoft Jet database (.mdb file) or other desktop ISAM database, or when you need to take advantage of Microsoft Jet's unique features, such as the ability to join data from different database formats.

The ODBCDirect workspace provides an alternative when you only need to execute queries or stored procedures against a back-end server, such as Microsoft SQL Server, or when your client application needs the specific capabilities of ODBC, such as batch updates or asynchronous query execution.

DAO Objects

There are 17 different DAO object types. You can declare new DAO object variables for any of the object types.

For example, the following Visual C++ code creates object variables for a CdbDatabase object, a dynaset-type CdbRecordset object, and a CdbField object:

CdbDBEngine      eng;
CdbDatabase      dbs;
CdbRecordset      rst;
CdbField         fld;
//
dbs = eng.OpenDatabase("Biblio.mdb");
rst = dbs.OpenRecordset("Authors", dbOpenDynaset);
fld = rst.Fields["Au_ID"];

DAO Collections

Each DAO object type other than CdbDBEngine also has a corresponding collection. A collection includes all the existing objects of that type. For example, the Recordsets collection contains all open CdbRecordset objects. Each collection is "owned" by another object at the next higher level in the hierarchy. A CdbDatabase object "owns" a Recordsets collection. Except for the CdbConnection and CdbError objects, every DAO object has a Properties collection.

Most DAO objects have default collections. For example, the default collection of a CdbRecordset object is the Fields collection. You can simplify your code by taking advantage of these defaults. For example, the following code returns the PubID field in the current record:

CdbField fld = rstExample["PubID"];

CdbDBEngine and CdbWorkspace Objects

All DAO objects are derived from the CdbDBEngine object. You can set the DefaultType property on the CdbDBEngine object to determine the workspace type (Microsoft Jet or ODBCDirect) to create on subsequent CreateWorkspace method calls, or you can override this property with the Type argument in the CreateWorkspace method itself. When your application creates a workspace, the appropriate library — the Microsoft Jet database engine or ODBC — is loaded into memory at that time.

You can open additional CdbWorkspace objects as needed. Each CdbWorkspace object has a user ID and password associated with it.


Using the Microsoft Jet Workspace

Opening a Database

To open a database, you simply open an existing CdbDatabase object or create a new one. This object can represent a Microsoft Jet database (.mdb file), an ISAM database (for example, Paradox), or an ODBC database connected through the Microsoft Jet database engine (also known as a "Microsoft Jet-connected ODBC database").

Data-Definition Language

You can use object variables and other DDL features to modify your database structure. For example, you can add a new CdbField object to an existing table with the following code:

CdbDBEngine   eng;
CdbDatabase   dbs;
CdbTableDef   tdf;
CdbField      fld;
// Open a database.
dbs = eng.OpenDatabase("Biblio.mdb");
// Open a TableDef.
tdf = dbs.TableDefs["Authors"];
// Create a new field.
fld = tdf.CreateField("Address", dbText, 20);
// Append field to the TableDef Fields collection.
tdf.Fields.Append(fld);

This code creates a new object variable for a CdbField object and adds it to a CdbTableDef object with the Append method. Because a CdbTableDef object contains the definition of a table, the table now has a field named Address for entering data. In much the same way, you can create new tables and new indexes.

Data Manipulation

DAO provides an excellent set of data manipulation tools. You can create a CdbRecordset object to conveniently query a database and manipulate the resulting set of records. The OpenRecordset method accepts an SQL string or a CdbQueryDef (stored query) name as a data source argument, or it can be opened from a CdbQueryDef object or a CdbTableDef object, using that object as its data source. The resulting CdbRecordset object features an extremely rich set of properties and methods with which to browse and modify data.

The CdbRecordset object is available in four different types — Table, Dynaset, Forward-Only, and Snapshot.

Transactions

All CdbDatabase objects opened against a CdbWorkspace object share a common transaction scope. That is, when you use the BeginTrans method on a CdbWorkspace object, it applies to all open databases within that CdbWorkspace object. In the same way, when you use the CommitTrans method against the CdbWorkspace, it applies to all open databases in the CdbWorkspace object.

Replication

You can use database replication to create and maintain replicas of a master Microsoft Jet database, using the Synchronize method to periodically update all or part of the replicas, or to copy new data from one replica to another. You can also restrict the update to only selected records, using the ReplicaFilter property, and then synchronize those records with the PopulatePartial method.

Security

You can restrict access to one or more .mdb databases or their tables using security settings established and managed by the Microsoft Jet database engine. In your code, you can establish CdbGroup and CdbUser objects to define the scope and level of permissions available to individual users on an object-by-object basis. For example, you can establish permissions for a specific user to provide read-only access to one table and full access to another.


Using the ODBCDirect Object Model

Connecting to a Database

A CdbConnection object is similar to a CdbDatabase object. In fact, a CdbConnection object and a CdbDatabase object represent different references to the same object, and properties on each of these two object types allow you to obtain a reference to the other corresponding object, which simplifies the task of converting ODBC client applications that use Microsoft Jet to use ODBCDirect instead. Use the OpenConnection method to connect to an ODBC data source. The resulting CdbConnection object contains information about the connection, such as the server name, the data source name, and so on.

Queries

Although DAO does not support stored queries in an ODBCDirect workspace, a compiled query can be created as a CdbQueryDef object and used to execute action queries, and can also be used to execute stored procedures on the server. The Prepare property lets you decide whether to create a private, temporary stored procedure on the server from a CdbQueryDef before actually executing the query.

Parameter queries can also be passed to the server, using CdbParameter objects on the CdbQueryDef. The Direction property lets you specify a CdbParameter as input, output, or both, or to accept a return value from a stored procedure.

Data Manipulation

Creating a CdbRecordset object is a convenient way to query a database and manipulate the resulting set of records. The OpenRecordset method accepts an SQL string or a CdbQueryDef object (stored query) as a data source argument. The resulting CdbRecordset object features an extremely rich set of properties and methods with which to browse and modify data.

The CdbRecordset object is available in four different types corresponding to ODBC cursor types as shown in the following table.

CdbRecordset Object Types | ODBC Cursor Types
Dynamic | Dynamic
Dynaset | Keyset
Forward-only | Forward-only
Snapshot | Static

A batch update cursor library is available for client applications that need to work with a cursor without holding locks on the server or without issuing update requests one record at a time. Instead, the client stores update information on many records in a local buffer (or "batch"), and then issues a batch update.

Asynchronous Method Execution

The Execute, MoveLast, OpenConnection, and OpenRecordset methods feature the dbRunAsync option. This allows your client application to do other tasks (such as loading forms, for example) while the method is executing. You can check the StillExecuting property to see whether the task is complete and terminate an asynchronous task with the Cancel method.


What's New in DAO?

DAO 3.5 introduces a new client/server connection mode, called "ODBCDirect." ODBCDirect establishes a connection directly to an ODBC data source, without loading the Microsoft Jet database engine into memory, and is useful in situations where specific features of ODBC are required.

For Microsoft Jet databases, there are also new interfaces to expose Microsoft Jet's new partial replication feature.

Note You can send DAO queries to a variety of different database servers with ODBCDirect, and the different servers will recognize slightly different dialects of SQL. Therefore, context-sensitive Help is no longer provided for Microsoft Jet SQL, although online Help for Microsoft Jet SQL is still included through the Help menu. Be sure to check the appropriate reference documentation for the SQL dialect of your database server when using either ODBCDirect connections or pass-through queries in Microsoft Jet-connected client/server applications.


New DAO 3.5 Features for ODBCDirect

  • CdbConnection object — A connection to an ODBC database.

  • Cancel method (on CdbConnection, CdbQueryDef, and CdbRecordset objects) — Cancels execution of an asynchronous operation.

  • NextRecordset method (on CdbRecordset objects) — Retrieves the next set of records, if any, returned by a query that returned multiple sets of records in an OpenRecordset call, and indicates whether it successfully retrieved another set of records.

  • OpenConnection method (on CdbWorkspace objects) — Opens a CdbConnection object on an ODBC data source.

  • BatchCollisionCount property (on CdbRecordset objects) — Returns the number of records that did not complete during the last batch update.

  • BatchCollisions property (on CdbRecordset objects) — Returns an array of bookmarks indicating the rows that generated collisions in the last batch update.

  • BatchSize property (on CdbRecordset objects) — Sets or returns the number of statements sent back to the server in each batch.

  • Connection property (on CdbDatabase and CdbRecordset objects) — Returns the CdbConnection object that corresponds to the CdbDatabase or that owns the CdbRecordset.

  • Database property (on CdbConnection objects) — Returns the name of the CdbDatabase object that corresponds to the CdbConnection.

  • DefaultCursorDriver property (on CdbWorkspace objects) — Sets or returns the type of cursor driver used for ODBCDirect CdbRecordset objects.

  • DefaultType property (on CdbDBEngine object) — Indicates what type of workspace (Microsoft Jet or ODBCDirect) will be created by the next CreateWorkspace method call.

  • Direction property (on CdbParameter objects) — Indicates whether a CdbParameter object represents an input parameter, an output parameter, or both, or if the parameter is the return value from a stored procedure.

  • MaxRecords property (on CdbQueryDef objects) — Sets or returns the maximum number of records to return from a query.

  • OriginalValue property (on CdbField objects) — Returns the value of a CdbField in the database that existed when the last batch update began.

  • Prepare property (on CdbQueryDef objects) — Returns a value that indicates whether the query should be prepared on the server as a temporary stored procedure with the ODBC SQLPrepare function prior to execution, or just executed using the ODBC SQLExecDirect function.

  • RecordStatus property (on CdbRecordset objects) — Returns a value that indicates the update status of the current record if it is part of a batch update.

  • StillExecuting property (on CdbConnection, CdbQueryDef, and CdbRecordset objects) — Returns a value indicating whether or not an asynchronous operation has finished executing.

  • UpdateOptions property (on CdbRecordset objects) — Returns a value that indicates how the WHERE clause is constructed for each record during a batch update and how the update should be executed.

  • VisibleValue property (on CdbRecordset objects) — Returns a value currently in the database that is newer than the OriginalValue property as determined by a batch update conflict.


New Capabilities with ODBCDirect

Server Connections

Available only in the ODBCDirect object model, the new CdbConnection object contains information about a connection to an ODBC data source, such as the server name, the data source name, and so on. It is similar to a CdbDatabase object and will look very familiar if you have ever opened a CdbDatabase object on an ODBC data source. In fact, a CdbConnection object and a CdbDatabase object represent different references to the same object. New properties on each of these two object types allow you to obtain a reference to the other corresponding object, which simplifies the task of converting existing ODBC client applications that use Microsoft Jet to use ODBCDirect instead.

Batch Updates

A new batch update cursor is available for client applications that need to work with a cursor without holding locks on the server or issue update requests one record at a time. Instead, the client stores update information on many records in a local buffer (or "batch"), and then issues a batch update.

Because of the time lag between opening a CdbRecordset and sending a batch of updates from that CdbRecordset back to the server, other users have an opportunity to change the original data before your changes are sent to the server, so your changes "collide" with another user's changes. Several new features are available to help you determine where such collisions have occurred following a batch update and to give you some options for resolving them.

Asynchronous Method Execution

The Execute, MoveLast, OpenConnection, and OpenRecordset methods feature the dbRunAsync option. This allows the client application to do other tasks (such as loading forms, and so on) while the method is executing. You can also poll to see whether the task is complete and terminate an asynchronous task.

Client Support for ODBC Cursors

Four different CdbRecordset types support the following ODBC cursor types:

ODBC cursor | CdbRecordset type
Dynamic | dbOpenDynamic (New in DAO 3.5)
Dynaset | dbOpenDynaset
Forward-Only | dbOpenForwardOnly (New in DAO 3.5)
Static | dbOpenSnapshot


New DAO 3.5 Features for the Microsoft Jet Database Engine

  • PopulatePartial method (on CdbDatabase objects) — Synchronizes any changes in a partial replica with the full replica, clears all records in the partial replica, and then repopulates the partial replica based on the current replica filters.

  • SetOption method (on CdbDBEngine object) — Overrides the registry values for the Microsoft Jet database engine for the duration of the current instance of DAO.

  • MaxRecords property (on CdbQueryDef objects) — Sets or returns the maximum number of records to return from a query.

  • ReplicaFilter property (on CdbTableDef objects) — Returns a value that indicates which subset of records is replicated to that table from a full replica.

  • PartialReplica property (on CdbRelation objects) — Indicates which CdbRelation object should be considered when populating a partial replica from a full replica.


New Capabilities with the Microsoft Jet Database Engine

Partial Replication

Version 3.5 of the Microsoft Jet database engine allows users to replicate portions of a table instead of the whole table (only row restrictions are permitted, not columns). There are two types of filters used in a partial replica — Boolean and relationship. Boolean filters select only rows that meet a certain criteria to limit the rows in a table that are replicated. DAO represents this filter with the ReplicaFilter property on a CdbTableDef. Relationship filters enforce a relationship between partially replicated tables to limit the rows in a table that are replicated. With DAO, you can set the PartialReplica property on a CdbRelation which allows that CdbRelation to be used in partial replication.

New CdbRecordset Type

In DAO 3.5, dbOpenForwardOnly is a new Type argument for the OpenRecordset method. This new CdbRecordset type behaves in the same way as a DAO 3.0 snapshot-type CdbRecordset opened with the dbForwardOnly option.

Run-time Registry Override

The new SetOption method allows you to override Microsoft Jet Registry settings at run time. This lets you fine tune Microsoft Jet query performance, timeout delays, and so on.


Customizing Windows Registry Settings for Data Access Objects

Note If your application cannot work correctly with the default functionality of the Microsoft Jet database engine, you may have to change the settings in the Windows Registry to suit your needs. The Windows Registry can also be used to tune the operation of the installable ISAM and ODBC driver.

You can modify the settings in the Windows Registry in three different ways. First, you can simply use Regedit.exe to overwrite the default settings which are established when the Microsoft Jet database engine is registered. This method of modification is the least flexible, because all applications which use the Microsoft Jet database engine have these new default settings.

The second method of modifying the Windows Registry settings is to create a Microsoft Jet portion in your application's registry tree to manage the settings for the Microsoft Jet database engine. The easiest way to accomplish this is to export the existing Microsoft Jet key and then import it into your application's tree with the Regedit.exe Export and Import commands. You can then alter any values you want to specify in your new registry tree. If you have supplied any values in the Engines subfolder, Microsoft Jet loads those settings when the application starts. Any values not entered in your client application's registry tree are loaded from shadow settings.

In order for your application to load the appropriate portion of the Windows Registry key you must specify the location with the DAO INIPath property. Your application must set the INIPath property before executing any other DAO code. The scope of this setting is limited to your application and can't be changed without restarting your application.

Note Although creating a Microsoft Jet portion in your application's registry is more flexible than overwriting the Microsoft Jet default entries, it still requires that you maintain the registry tree. Every time changes are required in the default settings, you will have to edit the Registry. In previous versions of Microsoft Jet these were the only two strategies for modifying the Registry.

DAO 3.5 provides a new way to modify default settings. Registry settings can now be modified at run time with the SetOption method. This is the recommended way to fine tune registry settings for your application. This method is both the most flexible approach and provides the developer with the most control over how the registry is changed. The SetOption method allows the user to specify new settings for any of the following default settings:

  • PageTimeout key

  • SharedAsyncDelay key

  • ExclusiveAsyncDelay key

  • LockRetry key

  • UserCommitSync key

  • ImplicitCommitSync key

  • MaxBufferSize key

  • MaxLocksPerFile key

  • LockDelay key

  • RecycleLVs

  • FlushTransactionTimeout key

By using the SetOption method, your application obtains the maximum flexibility and control. This approach allows you to create applications that are easier to maintain and tuned for maximum performance.

You can also edit the Windows Registry to specify the following:

  • Settings used for interaction with Microsoft FoxPro, Microsoft Excel, Lotus, Paradox, and dBASE databases. See Initializing the Paradox Database Driver, Initializing the Microsoft FoxPro Database Driver, Initializing the Microsoft Excel Driver, Initializing the Lotus Driver, and Initializing the dBASE Database Driver.

  • Settings used by Microsoft ODBC for interaction with SQL databases. See Initializing the Microsoft ODBC Database Driver.

  • Settings that affect how the Microsoft Jet database engine reads and saves data. See Initializing the Microsoft Jet 2.5 Database Engine Driver, and Initializing the Microsoft Jet 3.5 Database Engine Driver.

  • Settings used to control how the Microsoft Jet database engine interacts with the Internet and Microsoft Exchange. See Initializing the HTML (Internet) Data Source Driver and Initializing the Microsoft Exchange Data Source Driver.

  • Settings used to control how the Microsoft Jet database engine interacts with data imported as plain text. See Initializing the Text Data Source Driver.


Initializing the dBASE Database Driver

When you install the dBASE database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM format settings for the dBASE database driver.


dBASE Initialization Settings

The Jet\3.5\Engines\Xbase folder includes initialization settings for the Msxbse35.dll driver, used for access to external dBASE data sources. Typical settings for the entries in this folder are shown in the following example.

win32=<path>\MSXBSE35.dll
NetworkAccess=On
PageTimeout=600
INFPath=C:\DBASE\SYSTEM
CollatingSequence=ASCII
DataCodePage=OEM
Deleted=On
Century=Off
Date=MDY
Mark=47
Exact=Off

The Microsoft Jet database engine uses the Xbase folder entries as follows.

Entry | Description
win32 | The location of Msxbse35.dll. The full path is determined at the time of installation. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
NetworkAccess | A binary indicator for file locking preference. If NetworkAccess is set to 00, tables are opened for exclusive access, regardless of the settings of the OpenDatabase and OpenRecordset methods' exclusive argument. The default value is 01. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.
PageTimeout | The length of time between when data is placed in an internal cache and when it is invalidated. The value is specified in 100 millisecond units. The default is 600 units or 60 seconds. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
INFPath The full path to the .inf file directory. The Microsoft Jet database engine first looks for an .inf file in the directory containing the table. If the .inf file isn't in the database directory, it looks in the INFPath. If there is no INFPath, it uses whatever index files (.cdx or .mdx) it finds in the database directory. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.

This entry is not written by the installation procedure.
CollatingSequence | The collating sequence for all dBASE tables created or opened using the Microsoft Jet database engine. Possible values are ASCII and International. The default is ASCII. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
DataCodePage An indicator of how text pages are stored. Possible settings are:
  • OEM ? OemToAnsi and AnsiToOem conversions done.

  • ANSI ? OemToAnsi and AnsiToOem conversions not done.

The default is OEM. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
Deleted | A binary indicator that determines how records marked for deletion are handled by the Microsoft Jet database engine. A value of 01 corresponds to the dBASE command SET DELETED ON and indicates never to retrieve or position on a deleted record. A value of 00 corresponds to the dBASE command SET DELETED OFF and indicates to treat a deleted record like any other record. The default is 00. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.
Century | A binary indicator for formatting the century component of dates in cases where date-to-string functions are used in index expressions. A value of 01 corresponds to the dBASE command SET CENTURY ON and a value of 00 corresponds to the dBASE command SET CENTURY OFF. The default is 00. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.
Date | The date formatting style to use in cases where date-to-string functions are used in index expressions. The possible settings for this entry, which corresponds to the dBASE SET DATE command, are American, ANSI, British, French, DMY, German, Italian, Japan, MDY, USA, and YMD. The default is MDY. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
Mark The decimal value of the ASCII character used to separate date parts. The default depends on the Date setting as follows:
  • "/" (American, MDY)

  • "." (ANSI)

  • "/" (British, French, DMY)

  • "." (German)

  • "-" (Italian)

  • "/" (Japan, YMD)

  • "-" (USA)

A value of 0 specifies that the system should use the separator usually associated with the selected date format.

The default is 0. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
Exact | A binary indicator for string comparisons. A value of 01 corresponds to the dBASE command SET EXACT ON. A value of 00 corresponds to the dBASE command SET EXACT OFF. The default is 00. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.


dBASE ISAM Formats

The Jet\3.5\ISAM Formats\dBASE III folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Xbase
ExportFilter | REG_SZ | String | dBASE III (*.dbf)
ImportFilter | REG_SZ | String | dBASE III (*.dbf)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 01
IsamType | REG_DWORD | DWORD | 0
IndexDialog | REG_BINARY | Binary | 01
IndexFilter | REG_SZ | String | dBASE Index (*.ndx)
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextImport | REG_SZ | String | Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink | REG_SZ | String | Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport | REG_SZ | String | Export data from the current database into a dBASE III file. This process will overwrite the data if exported to an existing file.

'

The Jet\3.5\ISAM Formats\dBASE IV folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Xbase
ExportFilter | REG_SZ | String | dBASE IV (*.dbf)
ImportFilter | REG_SZ | String | dBASE IV (*.dbf)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 01
IsamType | REG_DWORD | DWORD | 0
IndexDialog | REG_BINARY | Binary | 01
IndexFilter | REG_SZ | String | dBASE Index (*.ndx; *.mdx)
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextImport | REG_SZ | String | Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink | REG_SZ | String | Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport | REG_SZ | String | Export data from the current database into a dBASE IV file. This process will overwrite the data if exported to an existing file.

The Jet\3.5\ISAM Formats\dBASE 5.x folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Xbase
ExportFilter | REG_SZ | String | dBASE 5 (*.dbf)
ImportFilter | REG_SZ | String | dBASE 5 (*.dbf)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 01
IsamType | REG_DWORD | DWORD | 0
IndexDialog | REG_BINARY | Binary | 01
IndexFilter | REG_SZ | String | dBASE Index (*.ndx; *.mdx)
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextImport | REG_SZ | String | Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink | REG_SZ | String | Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport | REG_SZ | String | Export data from the current database into a dBASE 5 file. This process will overwrite the data if exported to an existing file.

Note When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Lotus Driver

When you install the Lotus database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Lotus database driver.


Lotus Initialization Settings

The Jet\3.5\Engines\Lotus folder includes initialization settings for the Msltus35.dll driver, used for external access to Lotus spreadsheets. Typical settings for the entries under this heading are shown in the following example.

win32=<path>\MSLTUS35.dll
TypeGuessRows=8
ImportMixedTypes=Text
AppendBlankRows=4
FirstRowHasNames=Yes

The Microsoft Jet database engine uses the Lotus folder entries as follows.

Entry | Description
win32 | The location of Msltus35.dll. The full path is determined at the time of installation. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
TypeGuessRows | The number of rows to be checked for the data type. The data type is determined based on the most frequently found data type in the selection. If there is a tie, the data type is determined in the following order: Number, Currency, Date, Text, Long Text. If data is encountered that does not match the data type guessed for the column, it is returned as a Null value. On import, if a column has mixed data types, the entire column will be converted according to the ImportMixedTypes setting. The default number of rows to be checked is 8. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
ImportMixedTypes | Can be set to MajorityType or Text. If set to MajorityType, columns of mixed data types will be cast to the predominate data type on import. If set to Text, columns of mixed data types will be cast to Text on import. The default is Text. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
AppendBlankRows | The number of blank rows to be appended to the end of a WK1 worksheet before new data is added. For example, if AppendBlankRows is set to 4, Microsoft Jet will append 4 blank rows to the end of the worksheet before appending rows that contain data. Integer values for this setting can range from 0 to 16; the default is 01 (one additional row appended). Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
FirstRowHasNames | A binary value that indicates whether the first row of the table contains column names. A value of 01 indicates that, during import, column names are taken from the first row. A value of 00 indicates no column names in the first row; column names appear as F1, F2, F3, and so on. The default is 01. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.


Lotus ISAM Formats

The Jet\3.5\ISAM Formats\Lotus WK1 folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Lotus
ExportFilter | REG_SZ | String | Lotus 1-2-3 WK1 (*.wk1)
ImportFilter | REG_SZ | String | Lotus 1-2-3 (*.wk*;*.wj* )
CanLink | REG_BINARY | Binary | 00
OneTablePerFile | REG_BINARY | Binary | 00
IsamType | REG_DWORD | DWORD | 1
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 01
ResultTextImport | REG_SZ | String | Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextExport | REG_SZ | String | Export data from the current database into a Lotus 1-2-3 Version 2 file. This process will overwrite the data if exported to an existing file.

The Jet\3.5\ISAM Formats\Lotus WK3 folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Lotus
ExportFilter | REG_SZ | String | Lotus 1-2-3 WK3 (*.wk3)
CanLink | REG_BINARY | Binary | 00
OneTablePerFile | REG_BINARY | Binary | 00
IsamType | REG_DWORD | DWORD | 1
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 01
ResultTextExport | REG_SZ | String | Export data from the current database into a Lotus 1-2-3 Version 3 file. This process will overwrite the data if exported to an existing file.

The Jet\3.5\ISAM Formats\Lotus WK4 folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Lotus
CanLink | REG_BINARY | Binary | 00
OneTablePerFile | REG_BINARY | Binary | 00
IsamType | REG_DWORD | DWORD | 1
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 01

Note When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Microsoft Excel Driver

When you install the Microsoft Excel driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Microsoft Excel database driver.


Microsoft Excel Initialization Settings

The Jet\3.5\Engines\Excel folder includes initialization settings for the Msexcl35.dll driver, used for external access to Microsoft Excel worksheets. Typical settings for the entries in this folder are shown in the following example.

win32=<path>\MSEXCL35.dll
TypeGuessRows=8
ImportMixedTypes=Text
AppendBlankRows=1
FirstRowHasNames=Yes

The Microsoft Jet database engine uses the Excel folder entries as follows.

Entry | Description
win32 | The location of Msexcl35.dll. The full path is determined at the time of installation. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
TypeGuessRows | The number of rows to be checked for the data type. The data type is determined given the maximum number of kinds of data found. If there is a tie, the data type is determined in the following order: Number, Currency, Date, Text, Boolean. If data is encountered that does not match the data type guessed for the column, it is returned as a Null value. On import, if a column has mixed data types, the entire column will be cast according to the ImportMixedTypes setting. The default number of rows to be checked is 8. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
ImportMixedTypes | Can be set to MajorityType or Text. If set to MajorityType, columns of mixed data types will be cast to the predominate data type on import. If set to Text, columns of mixed data types will be cast to Text on import. The default is Text. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
AppendBlankRows | The number of blank rows to be appended to the end of a Version 3.5 or Version 4.0 worksheet before new data is added. For example, if AppendBlankRows is set to 4, Microsoft Jet will append 4 blank rows to the end of the worksheet before appending rows that contain data. Integer values for this setting can range from 0 to 16; the default is 01 (one additional row appended). Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
FirstRowHasNames | A binary value that indicates whether the first row of the table contains column names. A value of 01 indicates that, during import, column names are taken from the first row. A value of 00 indicates no column names in the first row; column names appear as F1, F2, F3, and so on. The default is 01. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.


Microsoft Excel ISAM Formats

The Jet\3.5\ISAM Formats\Excel 3.0 folder contains the following entries.

Entry name | Windows NT Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Excel
ExportFilter | REG_SZ | String | Microsoft Excel 3 (*.xls)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 00
IsamType | REG_DWORD | DWORD | 1
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 01
ResultTextExport | REG_SZ | String | Export data from the current database into a Microsoft Excel 3.0 file. This process will overwrite the data if exported to an existing file.

The Jet\3.5\ISAM Formats\Excel 4.0 folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Excel
ExportFilter | REG_SZ | String | Microsoft Excel 4 (*.xls)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 00
IsamType | REG_DWORD | DWORD | 1
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 01
ResultTextExport | REG_SZ | String | Export data from the current database into a Microsoft Excel 4.0 file. This process will overwrite the data if exported to an existing file.

The Jet\3.5\ISAM Formats\Excel 5.0 folder contains the following entries, which apply to Microsoft Excel versions 5.0 and 7.0.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Excel
ExportFilter | REG_SZ | String | Microsoft Excel 5-7 (*.xls)
ImportFilter | REG_SZ | String | Microsoft Excel (*.xls)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 00
IsamType | REG_DWORD | DWORD | 1
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 01
ResultTextImport | REG_SZ | String | Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink | REG_SZ | String | Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport | REG_SZ | String | Export data from the current database into a Microsoft Excel 5.0 file. This process will overwrite the data if exported to an existing file.

The Jet\3.5\ISAM Formats\Excel 8.0 folder contains the following entries, which apply to Microsoft Excel 97.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Excel
ExportFilter | REG_SZ | String | Microsoft Excel 97
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 00
IsamType | REG_DWORD | DWORD | 1
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 01
ResultTextExport | REG_SZ | String | Export data from the current database into a Microsoft Excel 97 file. This process will overwrite the data if exported to an existing file.

Note When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Microsoft FoxPro Database Driver

When you install the Microsoft FoxPro database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Microsoft FoxPro database driver.


Microsoft FoxPro Initialization Settings

The Jet\3.5\Engines\Xbase folder includes initialization settings for the Msxbse35.dll driver, used for access to external FoxPro data sources. Typical settings for the entries in this folder are shown in the following example.

win32=<path>\MSXBSE35.dll
NetworkAccess=On
PageTimeout=600
INFPath=C:\DBASE\SYSTEM
CollatingSequence=ASCII
DataCodePage=OEM
Deleted=Off
Century=Off
Date=MDY
Mark=47
Exact=Off

The Microsoft Jet database engine uses the Xbase folder entries as follows.

Entry | Description
win32 | The location of Msxbse35.dll. The full path is determined at the time of installation. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
NetworkAccess | A binary indicator for file locking preference. If NetworkAccess is set to 00, tables are opened for exclusive access, regardless of the settings of the OpenDatabase and OpenRecordset methods' exclusive argument. The default value is 01. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.
PageTimeout | The length of time between when data is placed in an internal cache and when it is invalidated. The value is specified in 100 millisecond units. The default is 600 units or 60 seconds. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
INFPath The full path to the .inf file directory. The Microsoft Jet database engine first looks for an .inf file in the directory containing the table. If the .inf file isn't in the database directory, it looks in the INFPath. If there is no INFPath, it uses whatever index files (.cdx or .mdx) it finds in the database directory. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.

This entry is not written by the installation procedure.
CollatingSequence | The collating sequence for all Microsoft FoxPro tables created or opened using Microsoft Jet. Possible values are ASCII and International. The default is ASCII. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
DataCodePage An indicator of how text pages are stored. Possible settings are:

OEM ? OemToAnsi and AnsiToOem conversions done.

ANSI ? OemToAnsi and AnsiToOem conversions not done.

The default is OEM. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
Deleted | A binary indicator that determines how records marked for deletion are handled by the Microsoft Jet database engine. A value of 01 corresponds to the Microsoft FoxPro command SET DELETED ON and indicates that Microsoft Jet will never retrieve or select a deleted record. A value of 00 corresponds to the Microsoft FoxPro command SET DELETED OFF and indicates that Microsoft Jet will treat a deleted record like any other record. The default is 00. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.
Century | A binary indicator for formatting the century component of dates in cases where date-to-string functions are used in index expressions. A value of 01 corresponds to the Microsoft FoxPro command SET CENTURY ON and a value of 00 corresponds to the Microsoft FoxPro command SET CENTURY OFF. The default is 00. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.
Date | The date formatting style to use in cases where date-to-string functions are used in index expressions. The possible settings for this entry, which corresponds to the Microsoft FoxPro SET DATE command, are American, ANSI, British, French, DMY, German, Italian, Japan, MDY, USA, and YMD. The default is MDY. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
Mark The decimal value of the ASCII character used to separate date parts. The default depends on the Date setting as follows:

"/" (American, MDY)

"." (ANSI)

"/" (British, French, DMY)

"." (German)

"-" (Italian)

"/" (Japan, YMD)

"-" (USA)

A value of 0 specifies that the system should use the separator usually associated with the selected date format.

The default is 0. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
Exact | A binary indicator for string comparisons. A value of 01 corresponds to the Microsoft FoxPro command SET EXACT ON. A value of 00 corresponds to the Microsoft FoxPro command SET EXACT OFF. The default is 00. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.


FoxPro ISAM Formats

The Jet\3.5\ISAM Formats\FoxPro 2.0 folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Xbase
ExportFilter | REG_SZ | String | Microsoft FoxPro 2.0 (*.dbf)
ImportFilter | REG_SZ | String | Microsoft FoxPro (*.dbf)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 01
IsamType | REG_DWORD | DWORD | 0
IndexDialog | REG_BINARY | Binary | 01
IndexFilter | REG_SZ | String | FoxPro Index (*.idx; *.cdx)
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextImport | REG_SZ | String | Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink | REG_SZ | String | Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport | REG_SZ | String | Export data from the current database into a Microsoft FoxPro 2.0 file. This process will overwrite the data if exported to an existing file.

The Jet\3.5\ISAM Formats\FoxPro 2.5 folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Xbase
ExportFilter | REG_SZ | String | Microsoft FoxPro 2.5 (*.dbf)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 01
IsamType | REG_DWORD | DWORD | 0
IndexDialog | REG_BINARY | Binary | 01
IndexFilter | REG_SZ | String | FoxPro Index (*.idx; *.cdx)
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextExport | REG_SZ | String | Export data from the current database into a Microsoft FoxPro 2.5 file. This process will overwrite the data if exported to an existing file.

The Jet\3.5\ISAM Formats\FoxPro 2.6 folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Xbase
ExportFilter | REG_SZ | String | Microsoft FoxPro 2.6 (*.dbf)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 01
IsamType | REG_DWORD | DWORD | 0
IndexDialog | REG_BINARY | Binary | 01
IndexFilter | REG_SZ | String | FoxPro Index (*.idx; *.cdx)
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextExport | REG_SZ | String | Export data from the current database into a Microsoft FoxPro 2.6 file. This process will overwrite the data if exported to an existing file.

The Jet\3.5\ISAM Formats\FoxPro 3.0 folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Xbase
ExportFilter | REG_SZ | String | Microsoft FoxPro 3.0 (*.dbf)
CanLink | REG_BINARY | Binary | 00
OneTablePerFile | REG_BINARY | Binary | 01
IsamType | REG_DWORD | DWORD | 0
IndexDialog | REG_BINARY | Binary | 01
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextExport | REG_SZ | String | Export data from the current database into a Microsoft FoxPro 3.0 file. This process will overwrite the data if exported to an existing file.

The Jet\3.5\ISAM Formats\FoxPro DBC folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Xbase
ExportFilter | REG_SZ | String | Microsoft FoxPro 3.0 (*.dbc)
CanLink | REG_BINARY | Binary | 00
OneTablePerFile | REG_BINARY | Binary | 00
IsamType | REG_DWORD | DWORD | 0
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextImport | REG_SZ | String | Import data from the external file into the current database. Changing data in the current database will not change data in the external file.

Note When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Microsoft Jet 2.5 Database Engine Driver

When you install the Microsoft Jet 2.5 Engine database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You must use the Registry Editor to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Microsoft Jet Engine database driver.

Note The installation procedure writes only one setting (win32) to the Jet\3.5\Engines\Jet 2.x folder; this is the only valid setting in this folder.


Microsoft Jet Engine Initialization Settings

The Jet\3.5\Engines\Jet 2.x folder contains the following entries.

ValueName | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Default
PageTimeOut | REG_DWORD | Integer | 5
LockedPageTimeOut | REG_DWORD | Integer | 5
LockRetry | REG_DWORD | Integer | 20
CommitLockRetry | REG_DWORD | Integer | 20
CursorTimeout | REG_DWORD | Integer | 5
IdleFrequency | REG_DWORD | Integer | 10
ForceOSFlush | REG_DWORD | Integer | 0
MaxBufferSize | REG_DWORD | Integer | 512
ReadAheadPages | REG_DWORD | Integer | 8

The Microsoft Jet database engine uses the following entry to determine the path to the database engine driver.

Entry | Description
win32 | Location of the database engine driver (.dll). The path is determined at the time of installation. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.

Additional initialization settings for the Microsoft Jet database engine are contained in the Jet\3.5\Engines\Jet 2.x folder.

Typical initialization settings for the entries in the Jet\3.5\Engines\Jet 2.x\ISAM folder are shown in the following example.

PageTimeout=5
LockedPageTimeout=5
CursorTimeout=5
LockRetry=20
CommitLockRetry=20
MaxBufferSize=512
ReadAheadPages=16
IdleFrequency=10
ForceOsFlush = 0

The following entries are used to configure the Microsoft Jet database engine.

Entry | Description
PageTimeout | The length of time between when data that is not read-locked is placed in an internal cache and when it's invalidated, expressed in 100 millisecond units. The default is 5 units (or 0.5 seconds). Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
LockedPageTimeout | The length of time between when data that is read-locked is placed in an internal cache and when it's invalidated, expressed in 100 millisecond units. The default is 5 units (or 0.5 seconds). Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
CursorTimeout | The length of time a reference to a page will remain on that page, expressed in 100 millisecond units. The default is 5 units (or 0.5 seconds). This setting applies only to databases created with version 1.x of the Microsoft Jet database engine. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
LockRetry | The number of times to repeat attempts to access a locked page before returning a lock conflict message. The default is 20 times; LockRetry is related to CommitLockRetry. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
CommitLockRetry The number of times the Microsoft Jet database engine attempts to acquire a lock on data to commit changes to that data. If the Microsoft Jet database engine cannot acquire a commit lock, changes to the data will be unsuccessful.

The number of attempts the Microsoft Jet database engine makes to get a commit lock is directly related to the LockRetry value. For each attempt made to acquire a commit lock, the Microsoft Jet database engine will make as many attempts as specified by the LockRetry value to acquire a lock. For example, if CommitLockRetry is set to 20 and LockRetry is set to 20, the Microsoft Jet database engine will try to acquire a commit lock as many as 20 times; for each of those attempts, the Microsoft Jet database engine will try to acquire a lock as many as 20 times, for a total of 400 attempts.

The default value for CommitLockRetry is 20. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
MaxBufferSize | The size of the database engine internal cache, measured in kilobytes (K). MaxBufferSize must be a whole number value between 9 and 4096, inclusive. The default is 512. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
ReadAheadPages | The number of pages to read ahead when performing sequential scans. The default is 16. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
ForceOSFlush | Any setting other than 0 means a commit or a write will force flushing the OS cache to disk. A setting of 0 (the default setting) means no force flush occurs. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
IdleFrequency | The amount of time, in 100 millisecond units, that Microsoft Jet will wait before releasing a read lock. The default is 10 units or one second. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.


Microsoft Jet Engine ISAM Formats

The Jet\3.5\ISAM Formats\Jet 2.x folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Jet 2.x
OneTablePerFile | REG_BINARY | Binary | 00
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 00
IsamType | REG_DWORD | DWORD | 0

Note When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Microsoft Jet 3.5 Database Engine Driver

The following sections describe initialization settings for the Microsoft Jet 3.5 database engine.

When MSJET35.DLL and MSRD2X35.DLL are registered, two entries are written to the \HKEY_LOCAL_MACHINES\Software\Microsoft\Jet\3.5\Engines folder. This is done automatically when Microsoft Access 97 is installed. These two entries are the following:

SystemDB = <path>\System.mdb
CompactBYPkey = 1

The Microsoft Jet database engine uses the following entries.

Entry | Description
SystemDB | Specifies the full path and file name of the workgroup information file. The default is the appropriate path followed by the file name System.mdb. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
CompactByPKey Specifies that when you compact tables they are copied in primary-key order, if a primary key exists on the table. If no primary key exists on a table, the tables are copied in base-table order.

A value of 0 indicates that tables should be compacted in base-table order; a non-zero value indicates that tables should be compacted in primary-key order, if a primary key exists. The default value is non-zero. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.

Note This setting only applies to compacting databases created with the Microsoft Jet database engine version 3.0 or later; when you compact databases created with the Microsoft Jet database engine version 2.x, the data is always copied in the order of the base table.


Configuring the Microsoft Jet Database Engine for ODBC Access

The following sections describe Windows registry settings for the Microsoft Jet database engine for connection to an ODBC database.


Initialization Settings for Microsoft Jet-connected ODBC Databases

The \HKEY_LOCAL_MACHINE\Software\Microsoft\Jet\3.5\Engines\ODBC folder contains initialization settings for the Microsoft Jet database engine.

Note Typical settings for the entries in the Jet\3.5\Engines\ODBC folder are shown in the following example.

LoginTimeout=20
QueryTimeout=60
ConnectionTimeout=600
AsyncRetryInterval=500
AttachCaseSensitive=0
AttachableObjects='TABLE','VIEW','SYSTEM TABLE','ALIAS','SYNONYM'
SnapshotOnly=0
TraceSQLMode=0
TraceODBCAPI=0
DisableAsync=1
JetTryAuth=1
PreparedInsert=0
PreparedUpdate=0
FastRequery=0

The Microsoft Jet database engine uses the ODBC entries as follows.

Entry | Description
LoginTimeout | The number of seconds a login attempt can continue before timing out. The default is 20 (values are of type REG_DWORD).
QueryTimeout | The number of seconds a query can run (total processing time) before timing out. If DisableAsync=0 (the default), then QueryTimeout is the number of seconds to wait for a response from the server between polls for query completion. The default is 60 (values are of type REG_DWORD).
ConnectionTimeout | The number of seconds a cached connection can remain idle before timing out. The default is 600 (values are of type REG_DWORD).
AsyncRetryInterval | The number of milliseconds between polls to determine if the server is done processing a query. This entry is used for asynchronous processing only. The default is 500 (values are of type REG_DWORD).
AttachCaseSensitive | An indicator of whether to match table names exactly when linking. Values are 0 (link the first table matching the specified name, regardless of case) and 1 (link a table only if the name matches exactly). The default is 0 (values are of type REG_DWORD).
AttachableObjects | A list of server object types to which linking will be allowed. The default is: 'TABLE', 'VIEW', 'SYSTEM TABLE', 'ALIAS', 'SYNONYM' (values are of type REG_SZ).
SnapshotOnly | An indicator of whether Recordset objects are forced to be of snapshot type. Values are 0 (allow dynasets) and 1 (force snapshots only). The default is 0 (values are of type REG_DWORD).
TraceSQLMode | An indicator of whether the Microsoft Jet database engine will trace SQL statements sent to an ODBC data source in SQLOUT.txt. Values are 0 (no) and 1 (yes). The default is 0 (values are of type REG_DWORD). This entry is interchangeable with SQLTraceMode.
TraceODBCAPI | An indicator of whether to trace ODBC API calls in ODBCAPI.txt. Values are 0 (no) and 1 (yes). The default is 0 (values are of type REG_DWORD).
DisableAsync | An indicator of whether to force synchronous query execution. Values are 0 (use asynchronous query execution if possible) and 1 (force synchronous query execution). The default is 1 (values are of type REG_DWORD).
JetTryAuth | An indicator of whether to try using the Microsoft Access user name and password to log in to the server before prompting. Values are 0 (no) and 1 (yes). The default is 1 (values are of type REG_DWORD).
PreparedInsert | An indicator of whether to use a prepared INSERT statement that inserts data in all columns. Values are 0 (use a custom INSERT statement that inserts only non-Null values) and 1 (use a prepared INSERT statement). The default is 0 (values are of type REG_DWORD). Using prepared INSERT statements can cause Nulls to overwrite server defaults and can cause triggers to execute on columns that weren't inserted explicitly.
PreparedUpdate | An indicator of whether to use a prepared UPDATE statement that updates data in all columns. Values are 0 (use a custom UPDATE statement that sets only columns that have changed) and 1 (use a prepared UPDATE statement). The default is 0 (values are of type REG_DWORD). Using prepared UPDATE statements can cause triggers to execute on unchanged columns.
FastRequery | An indicator of whether to use a prepared SELECT statement for parameterized queries. Values are 0 (no) and 1 (yes). The default is 0 (values are of type REG_DWORD).

Note When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Paradox Database Driver

When you install the Paradox database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly (unless necessary); use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Paradox database driver.


Paradox Initialization Settings

The Jet\3.5\Engines\Paradox folder includes initialization settings for the Mspdox35.dll driver, used for access to external Paradox data. Typical settings for the entries in this folder are shown in the following example.

win32=<path>\MSPDOX35.dll
PageTimeout=600
CollatingSequence=ASCII
DataCodePage=OEM
ParadoxUserName=Kimberly
ParadoxNetPath=P:\PDOXDB
ParadoxNetStyle=4.X

The Microsoft Jet database engine uses the Paradox folder entries as follows.

Entry | Description
win32 | The location of Mspdox35.dll. The full path is determined at the time of installation. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
PageTimeout | The length of time between when data is placed in an internal cache and when it is invalidated. The value is specified in 100 millisecond units. The default is 600 units or 60 seconds. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
CollatingSequence | The collating sequence for all Paradox tables created or opened using the Microsoft Jet database engine. Possible values are ASCII, International, Norwegian-Danish, and Swedish-Finnish. The CollatingSequence entry must match the collating sequence used when the Paradox table was built. The default is ASCII. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
DataCodePage An indicator of how text pages are stored. Possible settings are:
  • OEM ? OemToAnsi and AnsiToOem conversions done.

  • ANSI ? OemToAnsi and AnsiToOem conversions not done.

The default is OEM. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
ParadoxUserName The name to be displayed by Paradox if a table is locked by the Paradox ISAM and an interactive user accessing the data from Paradox (rather than the ISAM) attempts to place an incompatible lock. This entry isn't added if the computer isn't on a network. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.

Note If you indicate a ParadoxUserName, you must also specify a ParadoxNetPath and a ParadoxNetStyle or you'll receive an error when trying to access external Paradox data. Also, if you're accessing a Paradox database in multi-user mode over the network, you'll have to add or modify this registry entry manually.
ParadoxNetPath The full path to the directory containing the PARADOX.NET file (for Paradox 3.x) or the PDOXUSRS.NET file (for Paradox 4.x). This entry isn't added if the computer isn't on a network. Usually, you need to change the initial setting (added by the Setup program), which is a best guess at where the file might be. The full ParadoxNetPath (including the drive letter) must be consistent for all users sharing a particular database (directory). Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.

Note If you indicate a ParadoxNetPath, you must also specify a ParadoxUserName and a ParadoxNetStyle or you'll receive an error when trying to access external Paradox data. Also, if you're accessing a Paradox database in multi-user mode over the network, you'll have to add or modify this registry entry manually.
ParadoxNetStyle The network access style to use when accessing Paradox data. Possible values are:
  • 3.x

  • 4.x

Note that Paradox 3.x users can't set this to 4.x or the driver will use the wrong locking method. Paradox 5.0 users must use the 4.x ParadoxNetStyle setting to ensure proper locking behavior.

This entry isn't added if the computer isn't on a network. This entry should correspond to whatever version of Paradox the users in the group are using. It must be consistent for all users sharing a particular database (directory). The default is 4.x. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.

Note If you indicate a ParadoxNetStyle, you must also specify a ParadoxUserName and a ParadoxNetPath or you'll receive an error when trying to access external Paradox data.


Paradox ISAM Formats

The Jet\3.5\ISAM Formats\Paradox 3.x folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Paradox
ExportFilter | REG_SZ | String | Paradox 3 (*.db)
ImportFilter | REG_SZ | String | Paradox (*.db)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 01
IsamType | REG_DWORD | DWORD | 0
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextImport | REG_SZ | String | Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink | REG_SZ | String | Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport | REG_SZ | String | Export data from the current database into a Paradox 3 file. This process will overwrite the data if exported to an existing file.

The Jet\3.5\ISAM Formats\Paradox 4.x folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Paradox
ExportFilter | REG_SZ | String | Paradox 4 (*.db)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 01
IsamType | REG_DWORD | DWORD | 0
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextExport | REG_SZ | String | Export data from the current database into a Paradox 4 file. This process will overwrite the data if exported to an existing file.

The Jet\3.5\ISAM Formats\Paradox 5.x folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Paradox
ExportFilter | REG_SZ | String | Paradox 5 (*.db)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 01
IsamType | REG_DWORD | DWORD | 0
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextExport | REG_SZ | String | Export data from the current database into a Paradox 5 file. This process will overwrite the data if exported to an existing file.

Note When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Text Data Source Driver

When you install the Text Data Source database driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Text Data Source database driver.


Text Data Source Initialization Settings

The Jet\3.5\Engines\Text folder includes initialization settings for the Mstext35.dll driver, used for external access to text data files. Typical settings for the entries in this folder are shown in the following example.

win32=<path>\MSTEXT35.dll
MaxScanRows=25
FirstRowHasNames=True
CharacterSet=OEM
Format=CSVDelimited
Extensions=none,asc,csv,tab,txt
ExportCurrencySymbols=Yes

The Microsoft Jet database engine uses the Text folder entries as follows.

Entry | Description
win32 | The location of Mstext35.dll. The full path is determined at the time of installation. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
MaxScanRows | The number of rows to be scanned when guessing the column types. If set to 0, the entire file will be searched. The default is 25. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
FirstRowHasNames | A binary value that indicates whether the first row of the table contains column names. A value of 01 indicates that, during import, column names are taken from the first row. A value of 00 indicates no column names in the first row. The default is 01. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.
CharacterSet An indicator of how text pages are stored. Possible settings are:
  • OEM ? OemToAnsi and AnsiToOem conversions done.

  • ANSI ? OemToAnsi and AnsiToOem conversions not done.

The default is OEM. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
Format | Can be any of the following: TabDelimited, CSVDelimited, Delimited (<single character>). The single-character delimiter in the Delimited format can be any single character except a double quotation mark ("). The default is CSVDelimited. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
Extensions | The extension of whatever files are to be browsed when looking for text-based data. The default is txt, csv, tab, asc. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
ExportCurrencySymbols | A binary value that indicates whether the appropriate currency symbol is included when currency fields are exported. A value of 01 indicates that the symbol is included. A value of 00 indicates that only the numeric data is exported. The default is 01. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.


Text Data Source ISAM Formats

The Jet\3.5\ISAM Formats\Text folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Text
ExportFilter | REG_SZ | String | Text Files (*.txt; *.csv; *.tab; *.asc)
ImportFilter | REG_SZ | String | Text Files (*.txt; *.csv; *.tab; *.asc)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 01
IsamType | REG_DWORD | DWORD | 2
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextImport | REG_SZ | String | Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink | REG_SZ | String | Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.
ResultTextExport | REG_SZ | String | Export data from the current database into a text file. This process will overwrite the data if exported to an existing file.

Note When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Customizing the Schema.ini File

To read, import, or export text data, you need to create a Schema.ini file in addition to including the Text ISAM information in the .ini file. Schema.ini contains the specifics of a text data source: how the text file is formatted, how it is read at import time, and the default export format for files. The following examples show the layout for a fixed-width file, Filename.txt.

[Filename.txt]
ColNameHeader=False
Format=FixedLength
MaxScanRows=25
CharacterSet=OEM
Col1=columnname Char Width 24
Col2=columnname2 Date Width 9
Col3=columnname7 Float Width 10
Col4=columnname8 Integer Width 10
Col5=columnname9 LongChar Width 10

Similarly, the format for a delimited file is specified as follows:

[Delimit.txt]
ColNameHeader=True
Format=Delimited(!)
MaxScanRows=0
CharacterSet=OEM
Col1=username char width 50
Col2=dateofbirth Date width 9

If you are exporting data into a delimited text file, specify the format for that file as well.

[Export: My Special Export]
ColNameHeader=True
Format=TabDelimited
MaxScanRows=25
CharacterSet=OEM
DateTimeFormat=mm.dd.yy.hh.mm.ss
CurrencySymbol=Dm
CurrencyPosFormat=0
CurrencyDigits=2
CurrencyNegFormat=0
CurrencyThousandSymbol=,
CurrencyDecimalSymbol=.
DecimalSymbol=,
NumberDigits=2
NumberLeadingZeros=0

The My Special Export example refers to a specific export option; you can specify any variation of export options at connect time. This last example also corresponds to a data source name (DSN) that can be optionally passed at connect time. All three format sections can be included in the same .ini file.

The Microsoft Jet database engine uses the Schema.ini entries as follows.

Entry | Description
ColNameHeader | Can be set to either True (indicating that the first record of data specifies the column names) or False.
Format | Can be set to one of the following values: TabDelimited, CSVDelimited, Delimited (<single character>), or FixedLength. The delimiter specified for the Delimited file format can be any single character except a double quotation mark (").
MaxScanRows | Indicates the number of rows to be scanned when guessing the column data types. If this is set to 0, the entire file is searched.
CharacterSet | Can be set to OEM or ANSI, indicating whether the source file is written using an OEM or ANSI code page.
DateTimeFormat | Can be set to a format string indicating dates and times. This entry should be specified if all date/time fields in the import/export are handled with the same format. All of the Microsoft Jet database engine formats except AM and PM are supported. In the absence of a format string, the Windows Control Panel short date picture and time options are used.
CurrencySymbol | Indicates the currency symbol to be used for currency values in the text file. Examples include the dollar sign ($) and Dm. If this entry is absent, the default value in the Windows Control Panel is used.
CurrencyPosFormat | Can be set to any of the following values: Currency symbol prefix with no separation ($1) Currency symbol suffix with no separation (1$) Currency symbol prefix with one character separation ($ 1) Currency symbol suffix with one character separation (1 $) If this entry is absent, the default value in the Windows Control Panel is used.
CurrencyDigits | Specifies the number of digits used for the fractional part of a currency amount. If this entry is absent, the default value in the Windows Control Panel is used.
CurrencyNegFormat | Can be one of the following values: ($1) –$1 $–1 $1– (1$) –1$ 1–$ 1$– –1 $ –$ 1 1 $– $ 1– $ –1 1– $ ($ 1) (1 $) The dollar sign is shown for purposes of this example, but it should be replaced with the appropriate CurrencySymbol value in the actual program. If this entry is absent, the default value in the Windows Control Panel is used.
CurrencyThousandSymbol | Indicates the single-character symbol to be used for separating currency values in the text file by thousands. If this entry is absent, the default value in the Windows Control Panel is used.
CurrencyDecimalSymbol | Can be set to any single character that is used to separate the whole from the fractional part of a currency amount. If this entry is absent, the default value in the Windows Control Panel is used.
DecimalSymbol | Can be set to any single character that is used to separate the integer from the fractional part of a number. If this entry is absent, the default value in the Windows Control Panel is used.
NumberDigits | Indicates the number of decimal digits in the fractional portion of a number. If this entry is absent, the default value in the Windows Control Panel is used.
NumberLeadingZeros | Specifies whether a decimal value less than 1 and greater than –1 should contain leading zeros; this value can either be False (no leading zeros) or True.
Col1, Col2, ... | Lists the columns in the text file to be read. The format of this entry should be: Coln=columnName type [Width #] columnName: Column names with embedded spaces should be enclosed in quotation marks. type: Can be Bit, Byte, Short, Long, Currency, Single, Double, DateTime, Text, or Memo. In addition, the following ODBC Text Driver types are supported: Char (same as Text) Float (same as Double) Integer (same as Short) LongChar (same as Memo) Date date format

Note When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the HTML (Internet) Data Source Driver

When you install the HTML data source driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the HTML Data Source driver.


HTML Data Source Initialization Settings

The Jet\3.5\Engines\Text folder includes initialization settings for the Mstext35.dll driver, used for external access to tables stored within HTML files. Typical settings for the entries in this folder are shown in the following example.

win32=<path>\MSTEXT35.dll
MaxScanRows=25
FirstRowHasNames=False
CharacterSet=OEM
Format=TabDelimited
Extensions=none,asc,csv,tab,txt
ExportCurrencySymbols=Yes

The Microsoft Jet database engine uses the Text folder entries as follows.

Entry | Description
win32 | The location of Mstext35.dll. The full path is determined at the time of installation. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
MaxScanRows | The number of rows to be scanned when guessing the column types. If set to 0, the entire file will be searched. The default is 25. Values are of type DWORD for Windows 95 and Windows NT 4.0, and of type REG_DWORD for Windows NT 3.51.
FirstRowHas Names | A binary value that indicates whether the first row of the table contains column names. A value of 01 indicates that, during import, column names are taken from the first row. A value of 00 indicates no column names in the first row. The default is 01. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.
CharacterSet An indicator of how text pages are stored. Possible settings are:
  • OEM ? OemToAnsi and AnsiToOem conversions done.

  • ANSI ? OemToAnsi and AnsiToOem conversions not done.

The default is OEM. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
Format | Can be any of the following: TabDelimited, CSVDelimited, Delimited (<single character>). The single-character delimiter in the Delimited format can be any single character except a double quotation mark ("). The default is CSVDelimited. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
Extensions | The extension of whatever files are to be browsed when looking for text-based data. The default is txt, csv, tab, asc. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.
ExportCurrencySymbols | A binary value that indicates whether the appropriate currency symbol is included when currency fields are exported. A value of 01 indicates that the symbol is included. A value of 00 indicates that only the numeric data is exported. The default is 01. Values are of type Binary for Windows 95 and Windows NT 4.0, and of type REG_BINARY for Windows NT 3.51.


HTML Import ISAM Formats

The Jet\3.5\ISAM Formats\HTML Import folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Text
ImportFilter | REG_SZ | String | HTML Files (*.ht*)
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 00
IsamType | REG_DWORD | DWORD | 2
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextImport | REG_SZ | String | Import data from the external file into the current database. Changing data in the current database will not change data in the external file.
ResultTextLink | REG_SZ | String | Create a table in the current database that is linked to the external file. Changing data in the current database will change data in the external file.

Note When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


HTML Export ISAM Formats

The Jet\3.5\ISAM Formats\HTML Export folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Text
ExportFilter | REG_SZ | String | HTML Files (*.htm)
CanLink | REG_BINARY | Binary | 00
OneTablePerFile | REG_BINARY | Binary | 01
IsamType | REG_DWORD | DWORD | 2
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 00
ResultTextExport | REG_SZ | String | Export data from the current database into a text file. This process will overwrite the data if exported to an existing file.

Note When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


Initializing the Microsoft Exchange Data Source Driver

When you install the Microsoft Exchange Data Source driver, the Setup program writes a set of default values to the Windows Registry in the Engines and ISAM Formats subkeys. You should not modify these settings directly; use the setup program for your application to add, remove, or change these settings. The following sections describe initialization and ISAM Format settings for the Microsoft Exchange Data Source driver.


Microsoft Exchange Data Source Initialization Settings

The Jet\3.5\Engines\Exchange folder includes initialization settings for the Msexch35.dll driver, used for external access to Microsoft Exchange folders. The only entry in this folder is the following:

win32=<path>\MSEXCH35.dll

The Microsoft Jet database engine uses this Exchange folder to indicate the location of Msexch35.dll. The full path is determined at the time of installation. Values are of type String for Windows 95 and Windows NT 4.0, and of type REG_SZ for Windows NT 3.51.


Microsoft Exchange ISAM Formats

The Jet\3.5\ISAM Formats\Exchange 4.0 folder contains the following entries.

Entry name | Windows NT 3.51 Type | Windows 95 and Windows NT 4.0 Type | Value
Engine | REG_SZ | String | Exchange
CanLink | REG_BINARY | Binary | 01
OneTablePerFile | REG_BINARY | Binary | 00
IsamType | REG_DWORD | DWORD | 0
IndexDialog | REG_BINARY | Binary | 00
CreateDBOnExport | REG_BINARY | Binary | 00

Note When you change Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.


DAO Object Model for Microsoft Jet Workspaces


DAO Object Model for ODBCDirect Workspaces


DAO Objects and Collections Reference

DAO objects and collections provide a framework for using code to create and manipulate components of your database system. Objects and collections have properties that describe the characteristics of database components and methods that you use to manipulate them. Together these objects and collections form a hierarchical model of your database structure, which you can control programmatically.

Objects and collections provide different types of containment relations: Objects contain zero or more collections, all of different types; and collections contain zero or more objects, all of the same type. Although objects and collections are similar entities, the distinction differentiates the two types of relations.

In the following table, the type of collection in the first column contains the type of object in the second column. The third column describes what each type of object represents.

Collection | Object | Description
Connections | CdbConnection | Information about a connection to an ODBC data source (ODBCDirect workspaces only)
Containers | CdbContainer | Storage for information about a predefined object type (Microsoft Jet workspaces only)
Databases | CdbDatabase | An open database
None | CdbDBEngine | The Microsoft Jet database engine
Documents | CdbDocument | Information about a saved, predefined object (Microsoft Jet workspaces only)
Errors | CdbError | Information about any errors associated with this object
FieldsdvcolField | CdbField | A column that is part of a table, query, index, relation, or recordset
Groups | CdbGroup | A groupof user accounts (Microsoft Jet workspaces only)
Indexes | CdbIndex | Predefined ordering and uniqueness of values in a table (Microsoft Jet workspaces only)
Parameters | CdbParameter | A parameter for a parameter query
Properties | CdbProperty | A built-in or user-defined property
QueryDefs | CdbQueryDef | A saved query definition
Recordsets | CdbRecordset | The records in a base tableor query
Relations | CdbRelation | A relationship between fields in tables and queries (Microsoft Jet workspaces only)
TableDefs | CdbTableDef | A saved table definition (Microsoft Jet workspaces only)
Users | CdbUser | A user account(Microsoft Jet workspaces only)
Workspaces | CdbWorkspace | Asessionof the Microsoft Jet database engine


DAO Constants

DAO provides built-in constants that you can use with methods or properties. These constants all begin with the letters db and are documented with the method or property to which they apply.

Legend:

Read-only

Read/write

AllPermissions Property Constants (All are [image])

For any CdbContainer or CdbDocument object:

Constant | Allows user to
dbSecReadDef | Read the table definition, including column and index information
dbSecWriteDef | Modify or delete the table definition, including column and index information
dbSecRetrieveData | Retrieve data from the CdbDocument object
dbSecInsertData | Add records
dbSecReplaceData | Modify records
dbSecDeleteData | Delete records

The Databases container or any CdbDocument object in a Documents collection may include the following:

Constant | Allows user to
dbSecDeleteData | Delete records
dbSecDBAdmin | Replicate the database and change the database password
dbSecDBCreate | Create new databases; this setting is valid only on the Databases container in the workgroup information file (System.mdw)
dbSecDBExclusive | Have exclusive access to the database
dbSecDBOpen | Open the database

Attributes Property Constants

For any CdbField object, the Attributes property may include the following:

Constant | Description
dbFixedField | Fixed field size (default for Numeric fields)
dbVariableField | Variable field size (Text fields only)
dbAutoIncrField | New record field value incremented to unique Long integer (in a Microsoft Jet workspace, available only on CdbTableDef objects opened from .mdb files)
dbUpdatableField | Field is updatable
dbDescending | Field sorted in descending order (Microsoft Jet workspaces only)
dbHyperlinkField | Field contains hyperlink information (Memo fields in Microsoft Jet workspaces only)
dbSystemField | Field is a replication field (on a CdbTableDef object in Microsoft Jet databases only)

For any CdbRelation object, the Attributes property may include the following:

Constant | Description
dbRelationUnique | One-to-one relationship
dbRelationDontEnforce | Relationship not enforced (no referential integrity)
dbRelationInherited | Relationship exists in the database containing the two linked tables
dbRelationUpdateCascade | Updates cascade
dbRelationDeleteCascade | Deletions cascade

For any CdbTableDef object, the Attributes property may include the following:

Constant | Description
dbAttachExclusive | Opens a linked Microsoft Jet database engine table for exclusive use
dbAttachSavePWD | Saves user ID and password for linked remote table
dbSystemObject | System table
dbHiddenObject | Hidden table (for temporary use)
dbAttachedTable | Linked non-ODBC database table
dbAttachedODBC | Linked ODBC database table

CollatingOrder Property Constants (All are [image])

Constant | Collating order
dbSortArabic | Arabic
dbSortChineseSimplified | Simplified Chinese
dbSortChineseTraditional | Traditional Chinese
dbSortCyrillic | Russian
dbSortCzech | Czech
dbSortDutch | Dutch
dbSortGeneral | English, German, French, and Portuguese
dbSortGreek | Greek
dbSortHebrew | Hebrew
dbSortHungarian | Hungarian
dbSortIcelandic | Icelandic
dbSortJapanese | Japanese
dbSortKorean | Korean
dbSortNeutral | Neutral
dbSortNorwDan | Norwegian and Danish
dbSortPDXIntl | Paradox international
dbSortPDXNor | Paradox Norwegian and Danish
dbSortPDXSwe | Paradox Swedish and Finnish
dbSortPolish | Polish
dbSortSlovenian | Slovenian
dbSortSpanish | Spanish
dbSortSwedFin | Swedish and Finnish
dbSortThai | Thai
dbSortTurkish | Turkish
dbSortUndefined | Undefined or unknown

DefaultCursorDriver Property (All are [image])

Constant | Description
dbUseDefaultCursor | (Default) Uses server-side cursors if the server supports them; otherwise uses the ODBC Cursor Library
dbUseODBCCursor | Always uses the ODBC Cursor Library; this option provides better performance for small result sets, but degrades quickly for larger result sets
dbUseServerCursor | Always uses server-side cursors; for most large operations this option provides better performance, but might cause more network traffic
dbUseClientBatchCursor | Always uses the Microsoft Visual FoxPro Cursor Library; this option is required for performing batch updates
dbUseNoCursor | Opens all cursors (that is, CdbRecordset objects) as forward-only type, read-only, with a rowset size of 1; also known as "cursorless queries"

Direction Property Constants (All are [image])

Constant | Description
dbParamInput | (Default) Passes information to the procedure
dbParamInputOutput | Passes information both to and from the procedure
dbParamOutput | Returns information from the procedure as in an output parameter in SQL
dbParamReturnValue | Passes the return value from a procedure

EditMode Property Constants (All are [image])

Constant | Description
dbEditNone | No editing operation in effect
dbEditInProgress | Edit method invoked
dbEditAdd | AddNew method invoked

Permissions Property Constants (All are [image])

For any CdbContainer object, the Permissions property may include the following:

Constant | Description
dbSecNoAccess | Denies user access to the object
dbSecFullAccess | Allows user full access to the object
dbSecDelete | Allows user to delete the object
dbSecReadSec | Allows user to read the object's security-related information
dbSecWriteSec | Allows user to alter access permissions
dbSecWriteOwner | Allows user to change the Owner property setting

For any database CdbContainer, the Permissions property may include any of the following (All are [image]):

Constant | Allows user to
dbSecDBAdmin | Have permission to make a database replicable and change the database password
dbSecDBCreate | Create new databases (valid only on the databases Container object in the system database)
dbSecDBOpen | Open the database
dbSecDBExclusive | Exclusive access

For any tables CdbContainer, the Permissions property may include any of the following (All are [image]):

Constant | Allows user to
dbSecCreate | Create new tables (valid only with a CdbContainer object that represents a table or with the databases CdbContainer object in the system database)
dbSecReadDef | Read the table definition, including column and index information
dbSecWriteDef | Modify or delete the table definition, including column and index information
dbSecRetrieveData | Retrieve data from the document
dbSecInsertData | Add records
dbSecReplaceData | Modify records
dbSecDeleteData | Delete records

For any CdbDocument object, the Permissions property may include any of the following (All are [image]):

Constant | Allows user to
dbSecCreate | Create new tables (valid only with a CdbContainer object that represents a table)
dbSecDBCreate | Create new databases (valid only on the databases CdbContainer object in the system database)
dbSecDBOpen | Open the database
dbSecDBExclusive | Exclusive access
dbSecDelete | Delete the object
dbSecDeleteData | Delete records
dbSecFullAccess | Full access to the object
dbSecInsertData | Add records
dbSecReadDef | Read the table definition, including column and index information
dbSecReadSec | Read the object's security-related information
dbSecReplaceData | Modify records
dbSecRetrieveData | Retrieve data from the document
dbSecWriteDef | Modify or delete the table definition, including column and index information
dbSecWriteSec | Alter access permissions
dbSecWriteOwner | Change the Owner property setting

Prepare Property Constants (All are [image])

Constant | Description: The Statement is
dbQPrepare | (Default) Prepared (that is, the ODBC SQLPrepare API is called)
dbQUnprepare | Not prepared (that is, the ODBC SQLExecDirect API is called)

RecordStatus Property Constants (All are [image])

Constant | Description: The Record has
dbDBDeleted | Been deleted locally and in the database
dbDeleted | Been deleted, but not yet deleted in the database
dbRecordModified | Been modified and not updated in the database
dbRecordNew | Been inserted with the AddNew method, but not yet inserted into the database
dbRecordUnmodified | (Default) Not been modified or has been updated successfully

Type Property Constants

For any CdbField, CdbParameter, or CdbProperty object, the Type property may include any of the following (All are [image]):

Constant | Description
dbBigInt | Big Integer data (ODBCDirect only)
dbBinary | Binary data
dbBoolean | Boolean (True/False) data
dbByte | Byte (8-bit) data
dbChar | Character data (ODBCDirect only)
dbCurrency | Currency data
dbDate | Date value data
dbDecimal | Decimal data (ODBCDirect only)
dbDouble | Double-precision floating-point data
dbFloat | Floating-point data (ODBCDirect only)
dbGUID | GUID data
dbInteger | Integer data
dbLong | Long Integer data
dbLongBinary | Binary data (bitmap)
dbMemo | Memo data (extended text)
dbNumeric | Numeric data (ODBCDirect only)
dbSingle | Single-precision floating-point data
dbText | Text data (variable width)
dbTime | Data in time format (ODBCDirect only)
dbTimeStamp | Data in time and date format (ODBCDirect only)
dbVarBinary | Variable Binary data (ODBCDirect only)

For any CdbQueryDef object, the Type property may include any of the following (All are [image]):

Constant | Description
dbQAction | Action query
dbQAppend | Append query
dbQCompound | Compound query (ODBCDirect workspaces only)
dbQCrosstab | Crosstab query
dbQDDL | Data-definition language (DDL) query
dbQDelete | Delete query
dbQMakeTable | Make-table query
dbQProcedure | SQL procedure that executes a stored procedure (ODBCDirect workspaces only)
dbQSelect | Select query
dbQSetOperation | Set operation query
dbQSPTBulk | Bulk operation query
dbQSQLPassThrough | SQL pass-through query
dbQUpdate | Update query

For any CdbRecordset object, the Type property may include any of the following (All are [image]):

Constants | Indicates a
dbOpenDynamic | Dynaset-type CdbRecordset (ODBCDirect workspaces only)
dbOpenDynaset | Dynaset-type CdbRecordset
dbOpenForwardOnly | Forward-only type CdbRecordset
dbOpenSnapshot | Snapshot-type CdbRecordset
dbOpenTable | Table-type CdbRecordset (Microsoft Jet workspaces only)

UpdateOptions Property Constants (All are [image])

Constant | Uses
dbCriteriaKey | (Default) Just the key column(s) in the where clause
dbCriteriaModValues | Key column(s) and all updated columns in the where clause
dbCriteriaAllCols | Key column(s) and all the columns in the where clause
dbCriteriaTimeStamp | Just the timestamp column if available (will generate a run-time error if no timestamp column is in the result set)
dbCriteriaDeleteInsert | A pair of DELETE and INSERT statements for each modified row
dbCriteriaUpdate | (Default) An UPDATE statement for each modified row

CompactDatabase, CreateDatabase Methods Locale Argument Constants (All are [image])

Constant | Description
dbLangGeneral | English, German, French, Portuguese, Italian, and Modern Spanish
dbLangArabic | Arabic
dbLangChineseSimplified | Simplified Chinese
dbLangChineseTraditional | Traditional Chinese
dbLangCyrillic | Russian
dbLangCzech | Czech
dbLangDutch | Dutch
dbLangGreek | Greek
dbLangHebrew | Hebrew
dbLangHungarian | Hungarian
dbLangIcelandic | Icelandic
dbLangJapanese | Japanese
dbLangKorean | Korean
dbLangNordic | Nordic
dbLangNorwDan | Norwegian and Danish
dbLangPolish | Polish
dbLangSlovenian | Slovenian
dbLangSpanish | Spanish
dbLangSwedfin | Swedish and Finnish
dbLangThai | Thai
dbLangTurkish | Turkish

CompactDatabase Method Options Argument Constants (All are [image])

Constant | Description
dbDecrypt | Decrypts database while compacting
dbEncrypt | Encrypts database
dbVersion10 | Microsoft Jet database engine version 1.0
dbVersion11 | Microsoft Jet database engine version 1.1
dbVersion20 | Microsoft Jet database engine version 2.0
dbVersion30 | Microsoft Jet database engine version 3.0

CreateDatabase Method Options Argument Constants (All are [image])

Constant | Description
dbEncrypt | Encrypts database
dbVersion10 | Microsoft Jet database engine version 1.0
dbVersion11 | Microsoft Jet database engine version 1.1
dbVersion20 | Microsoft Jet database engine version 2.0
dbVersion30 | Microsoft Jet database engine version 3.0

CreateWorkspace Method Type Argument Constants

For any CdbWorkspace object Type property and CdbDBEngine object DefaultType property, use any of the following: (All are [image] )

Constant | Description
dbUseODBC | The next workspace created will use ODBCDirect
dbUseJet | The next workspace created will use the Microsoft Jet database engine

Execute Method Options Argument Constants (All are [image] )

Constant | Description
dbDenyWrite | Denies write permission to other users (Microsoft Jet workspaces only).
dbInconsistent | Allows inconsistent updates (Microsoft Jet workspaces only).
dbConsistent | Allows consistent updates (Microsoft Jet workspaces only).
dbSQLPassThrough | An SQL pass-through. Causes the SQL statement to be passed to an ODBC database for processing (Microsoft Jet workspaces only)
dbFailOnError | Rolls back updates if an error occurs (Microsoft Jet workspaces only)
dbSeeChanges | Generates a run-time error if another user is changing data you are editing (Microsoft Jet workspaces only)
dbRunAsync | Executes the query asynchronously (ODBCDirect workspaces only)
dbExecDirect | Executes the query without first calling the SQLPrepare ODBC function (ODBCDirect workspaces only)

Idle Method Optional Argument Constant (This is [image] )

Constant | Description
dbRefreshCache | Forces any pending writes to disk, and refreshes memory from current disk files

MakeReplica Method Optional Argument Constants (All are [image] )

Constant | Description
dbRepMakePartial | Creates a partial replica
dbRepMakeReadOnly | Makes replicable elements of new database read-only

OpenConnection and OpenDatabase Methods Option Argument Constants (All are [image] )

Constant | Description
dbDriverNoPrompt | The driver manager uses the connection string provided in connect. If sufficient information is not provided, a trappable error is returned
dbDriverPrompt | The driver manager displays the ODBC Data Sources dialog box. The connection string used to establish the connection is constructed from the data source name (DSN) selected and completed by the user via the dialog boxes.
dbDriverComplete | If the connection string provided includes the DSN keyword, the driver manager uses the string as provided in connect, otherwise it behaves as it does when dbDriverPrompt is specified
dbDriverCompleteRequired | (Default) Behaves like dbDriverComplete except the driver disables the controls for any information not required to complete the connection

OpenRecordset Method Type Argument Constants (All are [image] )

Constant | Description
dbOpenDynamic | Opens a dynamic-type CdbRecordset (ODBCDirect workspaces only)
dbOpenDynaset | Opens a dynaset-type CdbRecordset
dbOpenForwardOnly | Opens a forward-only type CdbRecordset
dbOpenSnapshot | Opens a snapshot-type CdbRecordset
dbOpenTable | Opens a table-type CdbRecordset (Microsoft Jet workspaces only)

OpenRecordset Method LockEdits Argument Constants (All are [image] )

Constant | Description
dbPessimistic | Pessimistic concurrency. Cursor uses the lowest level of locking sufficient to ensure the record can be updated.
dbReadOnly | Cursor is read-only. No updates are allowed.
dbOptimistic | Optimistic concurrency based on record ID. Cursor compares record ID in old and new records to determine if changes have been made since the record was last accessed.
dbOptimisticValue | Optimistic concurrency based on record values. Cursor compares data values in old and new records to determine if changes have been made since the record was last accessed (ODBCDirect workspaces only).
dbOptimisticBatch | Enables batch optimistic updates (ODBCDirect workspaces only).

OpenRecordset Method Options Argument Constants (All are [image] )

Constant | Description
dbDenyWrite | Prevents other users from changing CdbRecordset records (Microsoft Jet workspaces only)
dbDenyRead | Prevents other users from reading CdbRecordset records (table-type in Microsoft Jet workspaces only)
dbReadOnly | Opens the CdbRecordset as read-only (Microsoft Jet workspaces only)
dbAppendOnly | Allows user to add new records to the dynaset, but prevents user from reading existing records (dynaset-type in Microsoft Jet workspaces only)
dbInconsistent | Applies updates to all dynaset fields, even if other records are affected (dynaset- and snapshot-type in Microsoft Jet workspaces only)
dbConsistent | Applies updates only to those fields that will not affect other records in the dynaset (dynaset- and snapshot-type in Microsoft Jet workspaces only)
dbSQLPassThrough | Sends an SQL statement to an ODBC database (snapshot-type in Microsoft Jet workspaces only)
dbForwardOnly | Creates a forward-only scrolling snapshot-type CdbRecordset (snapshot-type in Microsoft Jet workspaces only)
dbSeeChanges | Generates a run-time error if another user is changing data you are editing (dynaset-type in Microsoft Jet workspaces only)
dbRunAsync | Executes the query asynchronously (ODBCDirect workspaces only)
dbExecDirect | Executes the query without first calling the SQLPrepare ODBC function (ODBCDirect workspaces only)

SetOption Method Parameter Constants (All are [image] )

Constant | Description
dbPageTimeout | PageTimeout key
dbSharedAsyncDelay | SharedAsyncDelay key
dbExclusiveAsyncDelay | ExclusiveAsyncDelay key
dbLockRetry | LockRetry key
dbUserCommitSync | UserCommitSync key
dbImplicitCommitSync | ImplicitCommitSync key
dbMaxBufferSize | MaxBufferSize key
dbMaxLocksPerFile | MaxLocksPerFile key
dbLockDelay | LockDelay key
dbRecycleLVs | RecycleLVs key
dbFlushTransactionTimeout | FlushTransactionTimeout key

Synchronize Method Exchange Argument Constants (All are [image] )

Constant | Description
dbRepExportChanges | Sends changes from current database to target database
dbRepImportChanges | Receives changes from target database
dbRepImpExpChanges | Sends and receives data in a bidirectional exchange
dbRepSyncInternet | Exchanges data between files connected via an Internet pathway

Update Method Type Argument Constants (All are [image] )

Constant | Description
dbUpdateRegular | (Default) Pending changes aren't cached and are written to disk immediately
dbUpdateBatch | All pending changes in the update cache are written to disk
dbUpdateCurrentRecord | Only the current record's pending changes are written to disk

CancelUpdate Method Type Argument Constants (All are [image] )

Constant | Description
dbUpdateRegular | (Default) Pending changes aren't cached and are written to disk immediately
dbUpdateBatch | All pending changes in the update cache are written to disk


CdbConnection Object (DAO)

CdbConnection Object

A CdbConnection object represents a connection to an ODBC database (ODBCDirect workspaces only).

Remarks

A CdbConnection is a non-persistent object that represents a connection to a remote database. The CdbConnection object is only available in ODBCDirect workspaces (that is, a CdbWorkspace object created with the type option set to dbUseODBC).

Note Code written for earlier versions of DAO can continue to use the CdbDatabase object for backward compatibility, but if you want the new features of a CdbConnection, revise the code to use the CdbConnection object. To help with code conversion, you can obtain a CdbConnection object reference from a CdbDatabase by reading the Connection property of the CdbDatabase object. Conversely, you can obtain a CdbDatabase object reference from the CdbConnection object’s Database property.

CdbConnection Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbConnection(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbConnection(const CdbConnection &);

Type | Description
const CdbConnection & | Reference to the object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbConnection(DAOConnection *pconn,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAOConnection * | pconn | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object when you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Connections Collection (DAO)

Connections Collection

A Connections collection contains the current CdbConnection objects of a CdbWorkspace object. (ODBCDirect workspaces only).

Remarks

When you open a CdbConnection object, it is automatically appended to the Connections collection of the CdbWorkspace. When you close a CdbConnection object with the Close method, it is removed from the Connections collection. Close all open CdbRecordset objects within the CdbConnection before closing it.

At the same time you open a CdbConnection object, a corresponding CdbDatabase object is created and appended to the Databases collection in the same CdbWorkspace, and vice versa. Similarly, when you close the CdbConnection, the corresponding CdbDatabase is deleted from the Databases collection, and so on.

The Name property setting of a CdbConnection is a string that specifies the path of the database file. To refer to a CdbConnection object in a collection by its ordinal number or by its Name property setting, use any of the following syntax forms:

Connections[0]

Connections["name"]

Note You can open the same data source more than once, creating duplicate names in the Connections collection. You should assign CdbConnection objects to object variables and refer to them by variable name.


CdbContainer Object (DAO)

CdbContainer Object

A CdbContainer object groups similar types of CdbDocument objects together.

Remarks

Each CdbDatabase object has a Containers collection consisting of built-in CdbContainer objects. Applications can define their own document types and corresponding containers (Microsoft Jet databases only); however, these objects may not always be supported through DAO.

Some of these CdbContainer objects are defined by the Microsoft Jet database engine while others may be defined by other applications. The following table lists the name of each CdbContainer object defined by the Microsoft Jet database engine and the type of information it contains.

CdbContainer | Contains information about
Databases | Saved databases
Tables | Saved tables and queries
Relations | Saved relationships

Note Don't confuse the CdbContainer objects listed in the preceding table with the collections of the same name. The Databases CdbContainer object refers to all saved database objects, but the Databases collection refers only to database objects that are open in a particular workspace.

Each CdbContainer object has a Documents collection containing CdbDocument objects that describe instances of built-in objects of the type specified by the CdbContainer. You typically use a CdbContainer object as an intermediate link to the information in the CdbDocument object. You can also use the Containers collection to set security for all CdbDocument objects of a given type.

With an existing CdbContainer object, you can:

  • Use the Name property to return the predefined name of the CdbContainer object.

  • Use the Owner property to set or return the owner of the CdbContainer object. To set the Owner property, you must have write permission for the CdbContainer object, and you must set the property to the name of an existing CdbUser or CdbGroup object.

  • Use the Permissions and UserName properties to set access permissions for the CdbContainer object; any CdbDocument object created in the Documents collection of a CdbContainer object inherits these access permission settings.

Because CdbContainer objects are built-in, you can't create new CdbContainer objects or delete existing ones.

To refer to a CdbContainer object in a collection by its ordinal number or by its Name property setting, use any of the following syntax forms:

Containers[0]

Containers["name"]

CdbContainer Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbContainer(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbContainer(const CdbContainer &);

Type | Description
const CdbContainer & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbContainer(DAOContainer *pctn,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAOContainer * | pctn | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object when you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Containers Collection (DAO)

Containers Collection

A Containers collection contains all of the CdbContainer objects that are defined in a database (Microsoft Jet databases only).

Remarks

Each CdbDatabase object has a Containers collection consisting of built-in CdbContainer objects. Some of these CdbContainer objects are defined by the Microsoft Jet database engine while others may be defined by other applications.


CdbDatabase Object (DAO)

CdbDatabase Object

A CdbDatabase object represents an open database.

Remarks

Use the CdbDatabase object and its methods and properties to manipulate an open database. In any type of database, you can:

  • Use the Execute method to run an action query.

  • Set the Connect property to establish a connection to an ODBC data source.

  • Set the QueryTimeout property to limit the length of time to wait for a query to execute against an ODBC data source.

  • Use the RecordsAffected property to determine how many records were changed by an action query.

  • Use the OpenRecordset method to execute a select query and create a Recordset object.

  • Use the Version property to determine which version of a database engine created the database.

With a Microsoft Jet database (.mdb file), you can also use other methods, properties, and collections to manipulate a CdbDatabase object, as well as create, modify, or get information about its tables, queries, and relationships. For example, you can:

  • Use the CreateTableDef and CreateRelation methods to create tables and relations, respectively.

  • Use the CreateProperty method to define new CdbDatabase properties.

  • Use the CreateQueryDef method to create a persistent or temporary query definition.

  • Use MakeReplica, Synchronize, and PopulatePartial methods to create and synchronize full or partial replicas of your database.

  • Set the CollatingOrder property to establish the alphabetic sorting order for character-based fields in different languages.

In an ODBCDirect workspace, you can use the CdbConnection property to obtain a reference to the CdbConnection object that corresponds to the CdbDatabase object.

Use the CreateDatabase method to create a persistent CdbDatabase object that is automatically appended to the Databases collection, thereby saving it to disk.

You don't need to specify the CdbDBEngine object when you use the OpenDatabase method.

Opening a database with linked tables doesn't automatically establish links to the specified external files or Microsoft Jet-connected ODBC data sources. You must either reference the table's CdbTableDef or CdbField objects or open a CdbRecordset object. If you can't establish links to these tables, a trappable error occurs. You may also need permission to access the database, or another user might have the database opened exclusively. In these cases, trappable errors occur.

You can also use the OpenDatabase method to open an external database (such as Microsoft Visual FoxPro, dBASE, and Paradox) directly instead of opening a Microsoft Jet database that has links to its tables.

Note Opening a CdbDatabase object directly on a Microsoft Jet-connected ODBC data source, such as Microsoft SQL Server, is not recommended because query performance is much slower than when using linked tables. However, performance is not a problem with opening a CdbDatabase object directly on an external ISAM database file, such as Visual FoxPro, Paradox, and so forth.

When a procedure that declares a CdbDatabase object has executed, local CdbDatabase objects are closed along with any open CdbRecordset objects. Any pending updates are lost and any pending transactions are rolled back, but no trappable error occurs. You should explicitly complete any pending transactions or edits and close CdbRecordset objects and CdbDatabase objects before exiting procedures that declare these object variables locally.

When you use one of the transaction methods (BeginTrans, CommitTrans, or Rollback) on the CdbWorkspace object, these transactions apply to all databases opened on the CdbWorkspace from which the CdbDatabase object was opened. If you want to use independent transactions, you must first open an additional CdbWorkspace object, and then open another CdbDatabase object in that CdbWorkspace object.

Note You can open the same data source or database more than once, creating duplicate names in the Databases collection. To avoid confusion, assign CdbDatabase objects to object variables and refer to them by variable name.

CdbDatabase Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbDatabase(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbDatabase(const CdbDatabase &);

Type | Description
const CdbDatabase & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbDatabase(DAODatabase *pdb,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAODatabase * | pdb | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object when you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Databases Collection (DAO)

Databases Collection

A Databases collection contains all open CdbDatabase objects opened or created in a CdbWorkspace object.

Remarks

When you open an existing CdbDatabase object or create a new one from a CdbWorkspace, it is automatically appended to the Databases collection. When you close a CdbDatabase object with the Close method, it is removed from the Databases collection, but not deleted from disk. Close all open CdbRecordset objects before closing a CdbDatabase object.

In a Microsoft Jet workspace, the Name property setting of a database is a string that specifies the path of the database file. In an ODBCDirect workspace, the Name property is the name of the corresponding CdbConnection object.

To refer to a CdbDatabase object in a collection by its ordinal number or by its Name property setting, use any of the following syntax forms:

Databases[0]

Databases["name"]

Note You can open the same data source or database more than once, creating duplicate names in the Databases collection. To avoid confusion, assign CdbDatabase objects to object variables and refer to them by variable name.


CdbDBEngine Object (DAO)

CdbDBEngine Object

The CdbDBEngine object is the top level object in the DAO object model.

Remarks

The CdbDBEngine object contains and controls all other objects in the hierarchy of DAO objects. You can't create additional CdbDBEngine objects, and the CdbDBEngine object isn't an element of any collection.

Note When you reference an ODBC data source directly through DAO, it is called an "ODBCDirect workspace." This is to distinguish it from an ODBC data source that you reference indirectly through the Microsoft Jet database engine, using a "Microsoft Jet workspace." Each method of accessing ODBC data requires one of two types of CdbWorkspace object; you can set the DefaultType property to choose the default type of CdbWorkspace object that you will create from the CdbDBEngine object. The CdbWorkspace type and associated data source determines which DAO objects, methods, and properties you can use.

With any type of database or connection, you can:

  • Use the Version property to obtain the DAO version number.

  • Use the LoginTimeout property to obtain or set the ODBC login timeout and the RegisterDatabase method to provide ODBC information to the Microsoft Jet database engine. You can use these features the same way, regardless of whether you connect to the ODBC data source through Microsoft Jet or through an ODBCDirect workspace.

  • Use the DefaultType property to set the default type of database connection that subsequently created CdbWorkspace objects will use — either Microsoft Jet or ODBCDirect.

  • Use the DefaultPassword and DefaultUser properties to set the user identification and password for the default CdbWorkspace object.

  • Use the CreateWorkspace method to create a new CdbWorkspace object. You can use optional arguments to override the settings of the DefaultType, DefaultPassword, and DefaultUser properties.

  • Use the OpenDatabase method to open a database in the default CdbWorkspace, and use the BeginTrans, Commit, and Rollback methods to control transactions on the default CdbWorkspace.

  • Use the Workspaces collection to reference specific CdbWorkspace objects.

  • Use the Errors collection to examine data access error details.

Other properties and methods are only available when you use DAO with the Microsoft Jet database engine. You can use them to control the Microsoft Jet database engine, manipulate its properties, and perform tasks on temporary objects that aren't elements of collections. For example, you can:

  • Use the CreateDatabase method to create a new Microsoft Jet CdbDatabase object.

  • Use the Idle method to enable the Microsoft Jet database engine to complete any pending tasks.

  • Use the CompactDatabase and RepairDatabase methods to maintain database files.

  • Use the IniPath and SystemDB properties to specify the location of Microsoft Jet Windows Registry information and the Microsoft Jet workgroup information file, respectively. The SetOption method allows you to override the Windows Registry settings for the Microsoft Jet database engine.

After you change the DefaultType and IniPath property settings, only subsequent CdbWorkspace objects will reflect these changes.

To refer to a collection that belongs to the CdbDBEngine object, or to refer to a method or property that applies to this object, use this syntax:

[CdbDBEngine.][collection method property]

CdbDBEngine Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbDBEngine(const CdbDBEngine &);

Type | Description
const CdbDBEngine & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbDBEngine(DAODBEngine *peng,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAODBEngine * | peng | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.

CONSTRUCTORCdbDBEngine(BOOL bPrivate = FALSE,

BOOL bStart = TRUE,

LPCTSTR pstrIniPath = Null,

LPCTSTR pstrDefUser = Null,

LPCTSTR pstrDefPW = Null,

LONG lType = dbUseJet);

Type | Argument | Description
BOOL | bPrivate =FALSE | Optional. Determines whether the Microsoft Jet engine is private or shared. Each private engine is a new instance of DAO. A private engine is one way to create secure access to data. A shared engine is common across all instances, enabling shared workspaces and databases, for example. If TRUE, then private.
BOOL | bStart =TRUE | Optional. A Boolean. TRUEThe Microsoft Jet engine is started when this object is created. FALSEThe Microsoft Jet engine must be started explicitly with the Start method.
LPCTSTR | pstrIniPath =Null | Optional. A pointer to a string that is a user-supplied portion of the Windows registry key containing Microsoft Jet database engine settings or parameters needed for installable ISAM databases.
LPCTSTR | pstrDefUser =Null | Optional. A pointer to a string that is the user name used to create the default Workspace when it is initialized.
LPCTSTR | pstrDefPW =Null | Optional. A pointer to a string that is the password used to create the default Workspace when it is initialized.
LONG | lType =dbUseJet | Optional. A value that determines whether the Workspace will be Microsoft Jet or ODBC (that is, dbUseJet or dbUseODBC).

This constructor creates an instance of the CdbDBEngine class.

This constructor is typically specified without parameters (that is, using all defaults) which makes it look like other DAO object constructors that take no parameters.

One reason to specify parameters is to create the Microsoft Jet Database Engine but postpone starting it. This enables you to acquire run-time information or avoid run-time conflicts when starting DAO from a user DLL. Another common reason to specify parameters is to create an ODBCDirect workspace.

Usage

#include <afxole.h>
#include <dbdao.h>

// Example 1:
CdbDBEngine   dben1a;             // Create an instance using defaults.
CdbDBEngine   dben1b( dben1a );   // Copy an existing instance.

// Example 2:
/* Create an instance of CdbDBEngine without using defaults.
   Specify: a private engine; don't start it when constructed; no IniPath, DefaultUser, or password, yet; explicitly request a Microsoft Jet workspace.
*/

CdbDBEngine dben2(TRUE,FALSE,NULL,NULL,NULL,dbUseJet);

// After getting IniPath, DefaultUser, and DefaultPassword from the // user, set the CdbDBEngine object with those values.

   dben2.SetIniPath(lpctstrIniPath);
   dben2.SetDefaultUser(lpstrDefaultUser);
   dben2.SetDefaultPassword(lpctstrPassword);

// Now, start the engine.
   dben2.Start();


Document Object (DAO)

CdbDocument Object

A CdbDocument object includes information about one instance of an object. The object can be a database, saved table, query, or relationship (Microsoft Jet databases only).

Remarks

Each CdbContainer object has a Documents collection containing CdbDocument objects that describe instances of built-in objects of the type specified by the CdbContainer. The following table lists the type of object each CdbDocument describes, the name of its CdbContainer object, and the type of information CdbDocument contains.

CdbDocument | CdbContainer | Contains information about
Database | Databases | Saved database
Table or query | Tables | Saved table or query
Relationship | Relations | Saved relationship

Note Don't confuse the CdbContainer objects listed in the preceding table with the collections of the same name. The Databases CdbContainer object refers to all saved database objects, but the Databases collection refers only to database objects that are open in a particular workspace.

With a CdbDocument object, you can:

  • Use the Name property to return the name that a user or the Microsoft Jet database engine gave to the object when it was created.

  • Use the Container property to return the name of the CdbContainer object that contains the CdbDocument object.

  • Use the Owner property to set or return the owner of the object. To set the Owner property, you must have write permission for the CdbDocument object, and you must set the property to the name of an existing CdbUser or CdbGroup object.

  • Use the UserName or Permissions properties to set or return the access permissions of a user or group for the object. To set these properties, you must have write permission for the CdbDocument object, and you must set the UserName property to the name of an existing CdbUser or CdbGroup object.

  • Use the DateCreated and LastUpdated properties to return the date and time when the CdbDocument object was created and last modified.

Because a CdbDocument object corresponds to an existing object, you can't create new CdbDocument objects or delete existing ones. To refer to a CdbDocument object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Documents[0]

Documents["name"]

CdbDocument Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbDocument(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbDocument(const CdbDocument &);

Type | Description
const CdbDocument & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbDocument(DAODocument *pdoc,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAODocument * | pdoc | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Documents Collection (DAO)

Documents Collection

A Documents collection contains all of the CdbDocument objects for a specific type of object (Microsoft Jet databases only).

Remarks

Each CdbContainer object has a Documents collection containing CdbDocument objects that describe instances of built-in objects of the type specified by the CdbContainer.

To refer to a CdbDocument object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Documents[0]

Documents["name"]


Error Object (DAO)

CdbError Object

A CdbError object contains details about data access errors, each of which pertains to a single operation involving DAO.

Remarks

Any operation involving DAO can generate one or more errors. For example, a call to an ODBC server might result in a database server error, an ODBC error, and a DAO error. As each error occurs, a CdbError object is placed in the Errors collection of the CdbDBEngine object. A single event can, therefore, result in several CdbError objects appearing in the Errors collection.

When a subsequent DAO operation generates an error, the Errors collection is cleared and one or more new CdbError objects are placed in the Errors collection. DAO operations that don't generate an error have no effect on the Errors collection.

The set of CdbError objects in the Errors collection describes one error. The first CdbError object is the lowest level error (the originating error), the second is the next higher level error, and so forth. For example, if an ODBC error occurs while trying to open a CdbRecordset object, the first CdbError object — Errors(0) — contains the lowest level ODBC error; subsequent errors contain the ODBC errors returned by the various layers of ODBC. In this case, the ODBC driver manager, and possibly the driver itself, return separate CdbError objects. The last CdbError object — Errors.Count-1 — contains the DAO error indicating that the object couldn't be opened.

Enumerating the specific errors in the Errors collection enables your error-handling routines to more precisely determine the cause and origin of an error, and take appropriate steps to recover. On both Microsoft Jet and ODBCDirect workspaces, you can read the CdbError object’s properties to obtain specific details about each error, including:

  • The Description property, which contains the text of the error alert that will be displayed on the screen if the error is not trapped.

  • The Number property, which contains the Long integer value of the error constant.

  • The Source property, which identifies the object that raised the error. This is particularly useful when you have several CdbError objects in the Errors collection following a request to an ODBC data source.

  • The HelpFile and HelpContext properties, which indicate the appropriate Microsoft Windows Help file and Help topic, respectively, (if any exist) for the error.

CdbError Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbError(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbError(const CdbError &);

Type | Description
const CdbError & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbError(DAOError *perr,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAOError * | perr | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Errors Collection (DAO)

Errors Collection

An Errors collection contains all stored CdbError objects, each of which pertains to a single operation involving DAO.

Remarks

Any operation involving DAO objects can generate one or more errors. As each error occurs, one or more CdbError objects are placed in the Errors collection of the CdbDBEngine object. When another DAO operation generates an error, the Errors collection is cleared and the new set of CdbError objects is placed in the Errors collection.

DAO operations that don't generate an error have no effect on the Errors collection.

Elements of the Errors collection aren't appended as they typically are with other collections, so the Errors collection doesn't support the Append and Delete methods.

The set of CdbError objects in the Errors collection describes one error. The first CdbError object is the lowest level error, the second is the next higher level, and so forth. For example, if an ODBC error occurs while trying to open a CdbRecordset object, the first error object contains the lowest level ODBC error; subsequent errors contain the ODBC errors returned by the various layers of ODBC. In this case, the ODBC driver manager, and possibly the driver itself, return separate CdbError objects. The last CdbError object contains the DAO error indicating that the object couldn't be opened.

Enumerating the specific errors in the Errors collection enables your error-handling routines to more precisely determine the cause and origin of an error, and take appropriate steps to recover.


Field Object (DAO)

CdbField Object

A CdbField object represents a column of data with a common data type and a common set of properties.

Remarks

The Fields collections of CdbIndex, CdbQueryDef, CdbRelation, and CdbTableDef objects contain the specifications for the fields those objects represent. The Fields collection of a CdbRecordset object represents the CdbField objects in a row of data or in a record. Use the CdbField objects in a CdbRecordset object to read and set values for the fields in the current record of the CdbRecordset object.

In both Microsoft Jet and ODBCDirect workspaces, you manipulate a field using a CdbField object and its methods and properties. For example, you can:

  • Use the OrdinalPosition property to set or return the presentation order of the CdbField object in a Fields collection. (This property is read-only for ODBCDirect databases.)

  • Use the Value property of a field in a CdbRecordset object to set or return stored data.

  • Use the AppendChunk and GetChunk methods and the FieldSize property to get or set a value in an OLE Object or Memo field of a CdbRecordset object.

  • Use the Type, Size, and Attributes properties to determine the type of data that can be stored in the field.

  • Use the SourceField and SourceTable properties to determine the original source of the data.

In Microsoft Jet workspaces, you can:

  • Use the ForeignName property to set or return information about a foreign field in a CdbRelation object.

  • Use the AllowZeroLength, DefaultValue, Required, ValidateOnSet, ValidationRule, or ValidationText properties to set or return validation conditions.

  • Use the DefaultValue property of a field on a CdbTableDef object to set the default value for this field when new records are added.

In ODBCDirect workspaces, you can:

  • Use the Value, VisibleValue, and OriginalValue properties to verify successful completion of a batch update.

To create a new CdbField object in a CdbIndex, CdbTableDef, or CdbRelation object, use the CreateField method.

When you access a CdbField object as part of a CdbRecordset object, data from the current record is visible in the CdbField object's Value property. To manipulate data in the CdbRecordset object, you don't usually reference the Fields collection directly; instead, you indirectly reference the Value property of the CdbField object in the Fields collection of the CdbRecordset object.

To refer to a CdbField object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Fields[0]

Fields["name"]

With the same syntax forms, you can also refer to the Value property of a CdbField object that you create and append to a Fields collection. The context of the field reference will determine whether you are referring to the CdbField object or the Value property of the CdbField object.

CdbField Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbField(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbField(const CdbField &);

Type | Description
const CdbField & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbField(DAOField *pfld,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAOField * | pfld | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Fields Collection (DAO)

Fields Collection

A Fields collection contains all stored CdbField objects of a CdbIndex, CdbQueryDef, CdbRecordset, CdbRelation, or CdbTableDef object.

Remarks

The Fields collections of the CdbIndex, CdbQueryDef, CdbRelation, and CdbTableDef objects contain the specifications for the fields those objects represent. The Fields collection of a CdbRecordset object represents the CdbField objects in a row of data or in a record. Use the CdbField objects in a CdbRecordset object to read and to set values for the fields in the current record of the CdbRecordset object.

To refer to a CdbField object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Fields[0]

Fields["name"]

With the same syntax forms, you can also refer to the Value property of a CdbField object that you create and append to a Fields collection. The context of the field reference will determine whether you are referring to the CdbField object or the Value property of the CdbField object.


Field Object, Fields Collection Summary (DAO)

CdbdbField Object, Fields Collection Summary

CdbField Object

A CdbField object contains this collection, these methods, and these properties.

Legend:

Feature available in Microsoft Jet workspaces only.
Feature available in ODBCDirect workspaces only.

Collection

Properties

Methods

The following table lists all of the CdbField object methods. The type of object whose Fields collection contains the CdbField object determines which methods are available.

Method | CdbIndex | CdbQueryDef | CdbRecordset | CdbRelation | CdbTableDef
AppendChunk |  |  |  |  |
CreateProperty |  |  |  |  |
GetChunk |  |  |  |  |
GetField |  |  |  |  |
SetField |  |  |  |  |

Properties

The following table lists all of the CdbField object properties. The type of object whose Fields collection contains the CdbField object determines which properties are available. All properties are read-only for CdbField objects appended to Fields collections of CdbIndex, CdbRelation, and CdbTableDef objects.

Read-only
Read/write

Property | CdbIndex | CdbQueryDef | CdbRecordset | CdbRelation | CdbTableDef
AllowZeroLength |  |  |  |  |
Attributes |  |  |  |  |
CollatingOrder |  |  |  |  |
CollectionIndex |  |  |  |  |
DataUpdatable |  |  |  |  |
DefaultValue |  |  |  |  |
FieldSize |  |  |  |  |
ForeignName |  |  |  |  |
Name |  |  |  |  |
OrdinalPosition |  |  |  |  |
OriginalValue |  |  | * |  |
Required |  |  |  |  |
Size |  |  |  |  |
SourceField |  |  |  |  |
SourceTable |  |  |  |  |
Type |  |  |  |  |
ValidateOnSet |  |  |  |  |
ValidationRule |  |  |  |  |
ValidationText |  |  |  |  |
Value |  |  |  |  |
VisibleValue |  |  | * |  |

Property | CdbIndex | CdbQueryDef | CdbRecordset | CdbRelation | CdbTableDef
AllowZeroLength |  |  |  |  |
Attributes |  |  |  |  |
CollatingOrder |  |  |  |  |
CollectionIndex |  |  |  |  |
DataUpdatable |  |  |  |  |
DefaultValue |  |  |  |  |
FieldSize |  |  |  |  |
ForeignName |  |  |  |  |
Name |  |  |  |  |
OrdinalPosition |  |  |  |  |
OriginalValue |  |  | * |  |
Required |  |  |  |  |
Size |  |  |  |  |
SourceField |  |  |  |  |
SourceTable |  |  |  |  |
Type |  |  |  |  |
ValidateOnSet |  |  |  |  |
ValidationRule |  |  |  |  |
ValidationText |  |  |  |  |
Value |  |  |  |  |
VisibleValue |  |  | * |  |

* These properties are only available in an ODBCDirect workspace whose DefaultCursorDriver property is set to dbUseClientBatchCursor.

Fields Collection

A Fields collection appears in each of the CdbTableDef, CdbQueryDef, CdbRecordset, CdbRelation, and CdbIndex objects, and contains these methods and this property.

Method | CdbIndex | CdbQueryDef | CdbRecordset | CdbRelation | CdbTableDef
Append |  |  |  |  |
Delete |  |  |  |  |
Refresh |  |  |  |  |

Property | CdbIndex | CdbQueryDef | CdbRecordset | CdbRelation | CdbTableDef
Count |  |  |  |  |


Group Object (DAO)

CdbGroup Object

A CdbGroup object represents a group of user accounts that have common access permissions when a CdbWorkspace object operates as a secure workgroup (Microsoft Jet workspaces only).

Remarks

You create CdbGroup objects and then use their names to establish and enforce access permissions for your databases, tables, and queries using the CdbDocument objects that represent the CdbDatabase, CdbTableDef, and CdbQueryDef objects with which you're working.

With the properties of a CdbGroup object, you can:

  • Use the Name property of an existing CdbGroup object to return its name. You can't return the PID property setting of an existing CdbGroup object.

  • Use the Name and PID properties of a newly created, unappended CdbGroup object to set the identity of that CdbGroup object.

You can append an existing CdbGroup object to the Groups collection in a CdbUser object to establish membership of a user account in that CdbGroup object. Alternatively, you can append a CdbUser object to the Users collection in a CdbGroup object to give a user account the global permissions of that group. If you use a Groups or Users collection other than the one to which you just appended an object, you may need to use the Refresh method to refresh the collection with current information from the database.

The Microsoft Jet database engine predefines three CdbGroup objects named Admins, Users, and Guests. To create a new CdbGroup object, use the CreateGroup method on a CdbUser or CdbWorkspace object.

To refer to a CdbGroup object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Groups[0]

Groups["name"]

CdbGroup Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbGroup(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbGroup(const CdbGroup &);

Type | Description
const CdbGroup & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbGroup(DAOGroup *pgrp,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAOGroup * | pgrp | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Groups Collection (DAO)

Groups Collection

A Groups collection contains all stored CdbGroup objects of a CdbWorkspace or user account (Microsoft Jet workspaces only).

Remarks

You can append an existing CdbGroup object to the Groups collection in a CdbUser object to establish membership of a user account in that CdbGroup object. Alternatively, you can append a CdbUser object to the Users collection in a CdbGroup object to give a user account the global permissions of that group. In either case, the existing CdbGroup object must already be a member of the Groups collection of the current CdbWorkspace object. If you use a Groups or Users collection other than the one to which you just appended an object, you may need to use the Refresh method to refresh the collection with current information from the database.

To refer to a CdbGroup object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Groups[0]

Groups["name"]


Index Object (DAO)

CdbIndex Object

CdbIndex objects specify the order of records accessed from database tables and whether or not duplicate records are accepted, providing efficient access to data. For external databases, CdbIndex objects describe the indexes established for external tables (Microsoft Jet workspaces only).

Remarks

The Microsoft Jet database engine uses indexes when it joins tables and creates CdbRecordset objects. Indexes determine the order in which table-type CdbRecordset objects return records, but they don't determine the order in which the Microsoft Jet database engine stores records in the base table or the order in which any other type of CdbRecordset object returns records.

With a CdbIndex object, you can:

  • Use the Required property to determine whether the Field objects in the index require values that are not Null, and then use the IgnoreNulls property to determine whether the Null values have index entries.

  • Use the Primary and Unique properties to determine the ordering and uniqueness of the CdbIndex object.

The Microsoft Jet database engine maintains all base table indexes automatically. It updates indexes whenever you add, change, or delete records from the base table. Once you create the database, use the CompactDatabase method periodically to bring index statistics up-to-date.

When accessing a table-type CdbRecordset object, specify the order of records using the object's CdbIndex property. Set this property to the Name property setting of an existing CdbIndex object in the Indexes collection. This collection is contained by the CdbTableDef object underlying the CdbRecordset object that you're populating.

Note You don't have to create indexes for a table, but for large, unindexed tables, accessing a specific record or processing joins can take a long time. Conversely, having too many indexes can slow down updates to the database as each of the table indexes is amended.

The Attributes property of each CdbField object in the index determines the order of records returned and, consequently, determines which access techniques to use for that index.

Each CdbField object in the Fields collection of a CdbIndex object is a component of the index. To define a new CdbIndex object, set its properties before you append it to a collection, making the CdbIndex object available for subsequent use.

Note You can modify the Name property setting of an existing CdbIndex object only if the Updatable property setting of the containing CdbTableDef object is TRUE.

When you set a primary key for a table, the Microsoft Jet database engine automatically defines it as the primary index. A primary index consists of one or more fields that uniquely identify all records in a table in a predefined order. Because the primary index field must be unique, the Microsoft Jet database engine automatically sets the Unique property of the primary CdbIndex object to TRUE. If the primary index consists of more than one field, each field can contain duplicate values, but the combination of values from all the indexed fields must be unique. A primary index consists of a key for the table and is always made up of the same fields as the primary key.

Important Make sure your data complies with the attributes of your new index. If your index requires unique values, make sure that there are no duplicates in existing data records. If duplicates exist, the Microsoft Jet database engine can't create the index; a trappable error results when you attempt to use the Append method on the new index.

When you create a relationship that enforces referential integrity, the Microsoft Jet database engine automatically creates an index with the Foreign property, set as the foreign key in the referencing table. After you've established a table relationship, the Microsoft Jet database engine prevents additions or changes to the database that violate that relationship. If you set the Attributes property of the CdbRelation object to allow cascading updates and cascading deletes, the Microsoft Jet database engine updates or deletes records in related tables automatically.

To create a new CdbIndex object

  1. Use the CreateIndex method on a CdbTableDef object.

  2. Use the CreateField method on the CdbIndex object to create a CdbField object for each field (column) to be included in the CdbIndex object.

  3. Set CdbIndex properties as needed.

  4. Append the CdbField object to the Fields collection.

  5. Append the CdbIndex object to the Indexes collection.

Note The Clustered property is ignored for databases that use the Microsoft Jet database engine, which doesn't support clustered indexes.

CdbIndex Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbIndex(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbIndex(const CdbIndex &);

Type | Description
const CdbIndex & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbIndex(DAOIndex *pidx,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAOIndex * | pidx | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Indexes Collection (DAO)

Indexes Collection

An Indexes collection contains all the stored CdbIndex objects of a CdbTableDef object (Microsoft Jet workspaces only).

Remarks

When you access a table-type CdbRecordset object, use the object's CdbIndex property to specify the order of records. Set this property to the Name property setting of an existing CdbIndex object in the Indexes collection of the CdbTableDef object underlying the CdbRecordset object.

Note You can use the Append or Delete method on an Indexes collection only if the Updatable property setting of the containing CdbTableDef object is True.

After you create a new CdbIndex object, use the Append method to add it to the CdbTableDef object's Indexes collection.

Important Make sure your data complies with the attributes of your new index. If your index requires unique values, make sure that there are no duplicates in existing data records. If duplicates exist, the Microsoft Jet database engine can't create the index; a trappable error results when you attempt to use the Append method on the new index.


Parameter Object (DAO)

CdbParameter Object

A CdbParameter object represents a value supplied to a query. The parameter is associated with a CdbQueryDef object created from a parameter query.

Remarks

CdbParameter objects allow you to change the arguments in a frequently run CdbQueryDef object without having to recompile the query.

Using the properties of a CdbParameter object, you can set a query parameter that can be changed before the query is run. You can:

  • Use the Name property to return the name of a parameter.

  • Use the Value property to set or return the parameter values to be used in the query.

  • Use the Type property to return the data type of the CdbParameter object.

  • Use the Direction property to set or return whether the parameter is an input parameter, an output parameter, or both.

In an ODBCDirect workspace, you can also:

  • Change the setting of the Type property. Doing so will also clear the Value property.

  • Use the Direction property to set or return whether the parameter is an input parameter, an output parameter, or both.

CdbParameter Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbParameter(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbParameter(const CdbParameter &);

Type | Description
const CdbParameter & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbParameter(DAOParameter *pprm,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAOParameter * | pprm | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Parameters Collection (DAO)

Parameters Collection

A Parameters collection contains all the CdbParameter objects of a CdbQueryDef object.

Remarks

The Parameters collection provides information only about existing parameters. You can't append objects to or delete objects from the Parameters collection.


Property Object (DAO)

CdbProperty Object

A CdbProperty object represents a built-in or user-defined characteristic of a DAO object.

Remarks

Every DAO object, except the CdbConnection and CdbError objects, contains a Properties collection, which has CdbProperty objects corresponding to built-in properties of that DAO object. The user can also define CdbProperty objects and append them to the Properties collection of some DAO objects. These CdbProperty objects (which are often just called properties) uniquely characterize that instance of the object.

You can create user-defined properties for the following objects:

  • CdbDatabase, CdbIndex, CdbQueryDef, and CdbTableDef objects.

  • CdbField objects in Fields collections of CdbQueryDef and CdbTableDef objects.

To add a user-defined property, use the CreateProperty method to create a CdbProperty object with a unique Name property setting. Set the Type and Value properties of the new CdbProperty object, and then append it to the Properties collection of the appropriate object. The object to which you are adding the user-defined property must already be appended to a collection. Referencing a user-defined CdbProperty object that has not yet been appended to a Properties collection will cause an error, as will appending a user-defined CdbProperty object to a Properties collection containing a CdbProperty object of the same name.

You can delete user-defined properties from the Properties collection, but you can't delete built-in properties.

Note A user-defined CdbProperty object is associated only with the specific instance of an object. The property isn't defined for all instances of objects of the selected type.

You can use the Properties collection of an object to enumerate the object's built-in and user-defined properties. You don't need to know beforehand exactly which properties exist or what their characteristics (Name and Type properties) are to manipulate them. However, if you try to read a write-only property, such as the Password property of a CdbWorkspace object, or try to read or write a property in an inappropriate context, such as the Value property setting of a CdbField object in the Fields collection of a CdbTableDef object, an error occurs.

The CdbProperty object also has four built-in properties:

  • The Name property — a String that uniquely identifies the property.

  • The Type property — an Integer that specifies the property data type.

  • The Value property — a Variant that contains the property setting.

  • The Inherited property — a Boolean that indicates whether the property is inherited from another object. For example, a CdbField object in a Fields collection of a CdbRecordset object can inherit properties from the underlying CdbTableDef or CdbQueryDef object.

To refer to a built-in CdbProperty object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Properties[0]

Properties["name"]

For a built-in property, you can also use this syntax:

object.name

Note For a user-defined property, you must use the Properties["name"] syntax.

With the same syntax forms, you can also refer to the Value property of a CdbProperty object. The context of the reference will determine whether you are referring to the CdbProperty object itself or the Value property of the CdbProperty object.

CdbProperty Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbProperty(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbProperty(const CdbProperty &);

Type | Description
const CdbProperty & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbProperty(DAOProperty *pprp,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAOProperty * | pprp | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Properties Collection (DAO)

Properties Collection

A Properties collection contains all the Property objects for a specific instance of an object.

Remarks

Every DAO object, except the CdbConnection and CdbError objects, contains a Properties collection, which has certain built-in CdbProperty objects. These CdbProperty objects (which are often just called properties) uniquely characterize that instance of the object.

In addition to the built-in properties, you can also create and add your own user-defined properties. To add a user-defined property to an existing instance of an object, first define its characteristics with the CreateProperty method, and then add it to the collection with the Append method. Referencing a user-defined CdbProperty object that has not yet been appended to a Properties collection will cause an error, as will appending a user-defined CdbProperty object to a Properties collection containing a CdbProperty object of the same name.

You can use the Delete method to remove user-defined properties from the Properties collection, but you can't remove built-in properties.

Note A user-defined CdbProperty object is associated only with the specific instance of an object. The property isn't defined for all instances of objects of the selected type.

You can use the Properties collection of an object to enumerate the object's built-in and user-defined properties. You don't need to know beforehand exactly which properties exist or what their characteristics (Name and Type properties) are to manipulate them. However, if you try to read a write-only property, such as the Password property of a CdbWorkspace object, or try to read or write a property in an inappropriate context, such as the Value property setting of a CdbField object in the Fields collection of a CdbTableDef object, an error occurs.

To refer to a built-in CdbProperty object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Properties[0]

Properties["name"]

Note For a user-defined property, use the full object.Properties["name"] syntax.

With the same syntax forms, you can also refer to the Value property of a CdbProperty object. The context of the reference will determine whether you are referring to the CdbProperty object itself or the Value property of the CdbProperty object.


QueryDef Object (DAO)

CdbQueryDef Object

A CdbQueryDef object is a stored definition of a query in a Microsoft Jet database or a temporary definition of a query in an ODBCDirect workspace.

Remarks

You can use the CdbQueryDef object to define a query. For example, you can:

  • Use the SQL property to set or return the query definition.

  • Use the CdbQueryDef object's Parameters collection to set or return query parameters.

  • Use the Type property to return a value indicating whether the query selects records from an existing table, makes a new table, inserts records from one table into another table, deletes records, or updates records.

  • Use the MaxRecords property to limit the number of records returned from a query.

  • Use the ODBCTimeout property to indicate how long to wait before the query returns records. The ODBCTimeout property applies to any query that accesses ODBC data.

In a Microsoft Jet workspace, you can also:

  • Use the ReturnsRecords property to indicate that the query returns records. The ReturnsRecords property is only valid on SQL pass-through queries.

  • Use the Connect property to make an SQL pass-through query to an ODBC database.

In an ODBCDirect workspace, you can also:

  • Use the Prepare property to determine whether to invoke the ODBC SQLPrepare API when the query is executed.

  • Use the CacheSize property to cache records returned from a query.

You can also create temporary CdbQueryDef objects. Unlike permanent CdbQueryDef objects, temporary CdbQueryDef objects are not saved to disk or appended to the QueryDefs collection. Temporary CdbQueryDef objects are useful for queries that you must run repeatedly during run time, but do not not need to save to disk, particularly if you create their SQL statements during run time.

You can think of a permanent CdbQueryDef object in a Microsoft Jet workspace as a compiled SQL statement. If you execute a query from a permanent CdbQueryDef object, the query will run faster than if you run the equivalent SQL statement from the OpenRecordset method. This is because the Microsoft Jet database engine doesn't need to compile the query before executing it.

The preferred way to use the native SQL dialect of an external database engine accessed through the Microsoft Jet database engine is through CdbQueryDef objects. For example, you can create a Microsoft SQL Server query and store it in a CdbQueryDef object. When you need to use a non-Microsoft Jet database engine SQL query, you must provide a Connect property string that points to the external data source. Queries with valid Connect properties bypass the Microsoft Jet database engine and pass the query directly to the external database server for processing.

To create a new CdbQueryDef object, use the CreateQueryDef method. In a Microsoft Jet workspace, if you supply a string for the name argument or, if you explicitly set the Name property of the new CdbQueryDef object to a non–zero-length string, you will create a permanent CdbQueryDef that will automatically be appended to the QueryDefs collection and saved to disk. Supplying a zero-length string as the name argument or explicitly setting the Name property to a zero-length string will result in a temporary CdbQueryDef object.

In an ODBCDirect workspace, a CdbQueryDef is always temporary. The QueryDefs collection contains all open CdbQueryDef objects. When a CdbQueryDef is closed, it is automatically removed from the QueryDefs collection.

To refer to a CdbQueryDef object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

QueryDefs[0]

QueryDefs["name"]

You can refer to temporary CdbQueryDef objects only by the object variables that you have assigned to them.

CdbQueryDef Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbQueryDef(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbQueryDef(const CdbQueryDef &);

Type | Description
const CdbQueryDef & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbQueryDef(DAOQueryDef *pqd,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAOQueryDef * | pqd | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.

Note In DAO the default collection for the CdbQueryDef object is Parameters. However, in the DAO SDK the default collection for the CdbQueryDef object is Fields. The default collection is accessed by applying the subscript ([ ]) operator to the CdbQueryDef object.


QueryDefs Collection (DAO)

QueryDefs Collection

A QueryDefs collection contains all CdbQueryDef objects of a CdbDatabase object in a Microsoft Jet database, and all CdbQueryDef objects of a CdbConnection object in an ODBCDirect workspace.

Remarks

To create a new CdbQueryDef object, use the CreateQueryDef method. In a Microsoft Jet workspace, if you supply a string for the name argument or if you explicitly set the Name property of the new CdbQueryDef object to a non–zero-length string, you will create a permanent CdbQueryDef that will automatically be appended to the QueryDefs collection and saved to disk. Supplying a zero-length string as the name argument or explicitly setting the Name property to a zero-length string will result in a temporary CdbQueryDef object.

In an ODBCDirect workspace, a CdbQueryDef is always temporary. The QueryDefs collection contains all open CdbQueryDef objects. When a CdbQueryDef is closed, it is automatically removed from the QueryDefs collection.

To refer to a CdbQueryDef object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

QueryDefs[0]

QueryDefs["name"]

You can refer to temporary CdbQueryDef objects only by the object variables that you have assigned to them.


Recordset Object (DAO)

CdbRecordset Object

A CdbRecordset object represents the records in a base table or the records that result from running a query.

Remarks

You use CdbRecordset objects to manipulate data in a database at the record level. When you use DAO objects, you manipulate data almost entirely using CdbRecordset objects. All CdbRecordset objects are constructed using records (rows) and fields (columns). There are five types of CdbRecordset objects:

  • Table-type CdbRecordset — representation in code of a base table that you can use to add, change, or delete records from a single database table (Microsoft Jet workspaces only).

  • Dynaset-type CdbRecordset — the result of a query that can have updatable records. A dynaset-type CdbRecordset object is a dynamic set of records that you can use to add, change, or delete records from an underlying database table or tables. A dynaset-type CdbRecordset object can contain fields from one or more tables in a database. This type corresponds to an ODBC keyset cursor.

  • Snapshot-type CdbRecordset — a static copy of a set of records that you can use to find data or generate reports. A snapshot-type CdbRecordset object can contain fields from one or more tables in a database, but can't be updated. This type corresponds to an ODBC static cursor.

  • Forward-only–type CdbRecordset — identical to a snapshot except that no cursor is provided. You can only scroll forward through records. This improves performance in situations where you only need to make a single pass through a result set. This type corresponds to an ODBC forward-only cursor.

  • Dynamic-type CdbRecordset — a query result set from one or more base tables in which you can add, change, or delete records from a row-returning query. Further, records other users add, delete, or edit in the base tables also appear in your CdbRecordset. This type corresponds to an ODBC dynamic cursor (ODBCDirect workspaces only).

You can choose the type of CdbRecordset object you want to create using the type argument of the OpenRecordset method.

In a Microsoft Jet workspace, if you don't specify a type, DAO attempts to create the type of CdbRecordset with the most functionality available, starting with table. If this type isn’t available, DAO attempts a dynaset, then a snapshot, and finally a forward-only–type CdbRecordset object.

In an ODBCDirect workspace, if you don't specify a type, DAO attempts to create the type of CdbRecordset with the fastest query response, starting with forward-only. If this type isn't available, DAO attempts a snapshot, then a dynaset, and finally a dynamic-type CdbRecordset object.

When creating a CdbRecordset object using a non-linked CdbTableDef object in a Microsoft Jet workspace, table-type CdbRecordset objects are created. Only dynaset-type or snapshot-type CdbRecordset objects can be created with linked tables or tables in Microsoft Jet-connected ODBC databases.

A new CdbRecordset object is automatically added to the Recordsets collection when you open the object, and is automatically removed when you close it.

Note If you use variables to represent a CdbRecordset object and the CdbDatabase object that contains the CdbRecordset, make sure the variables have the same scope, or lifetime. For example, if you declare a public variable that represents a CdbRecordset object, make sure the variable that represents the CdbDatabase containing the CdbRecordset is also public.

You can create as many CdbRecordset object variables as needed. Different CdbRecordset objects can access the same tables, queries, and fields without conflicting.

Dynaset-, snapshot-, and forward-only–type CdbRecordset objects are stored in local memory. If there isn't enough space in local memory to store the data, the Microsoft Jet database engine saves the additional data to TEMP disk space. If this space is exhausted, a trappable error occurs.

The default collection of a CdbRecordset object is the Fields collection, and the default property of a CdbField object is the Value property. Use these defaults to simplify your code.

When you create a CdbRecordset object, the current record is positioned to the first record if there are any records. If there are no records, the RecordCount property setting is 0, and the BOF and EOF property settings are TRUE.

You can use the MoveNext, MovePrevious, MoveFirst, and MoveLast methods to reposition the current record. Forward-only–type CdbRecordset objects support only the MoveNext method. When using the Move methods to visit each record (or "walk" through the CdbRecordset), you can use the BOF and EOF properties to check for the beginning or end of the CdbRecordset object.

With dynaset- and snapshot-type CdbRecordset objects in a Microsoft Jet workspace, you can also use the Find methods, such as FindFirst, to locate a specific record based on criteria. If the record isn't found, the NoMatch property is set to TRUE. For table-type CdbRecordset objects, you can scan records using the Seek method.

The Type property indicates the type of CdbRecordset object created, and the Updatable property indicates whether you can change the object's records.

Information about the structure of a base table, such as the names and data types of each CdbField object and any CdbIndex objects, is stored in a TableDef object.

To refer to a CdbRecordset object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Recordsets[0]

Recordsets["name"]

Note You can open a CdbRecordset object from the same data source or database more than once, creating duplicate names in the Recordsets collection. You should assign CdbRecordset objects to object variables and refer to them by variable name.

CdbRecordset Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbRecordset(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbRecordset(const CdbRecordset &);

Type | Description
const CdbRecordset & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbRecordset(DAORecordset *prs,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAORecordset * | prs | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Recordsets Collection (DAO)

Recordsets Collection

A Recordsets collection contains all open CdbRecordset objects in a CdbDatabase object.

Remarks

When you use DAO objects, you manipulate data almost entirely using CdbRecordset objects.

A new CdbRecordset object is automatically added to the Recordsets collection when you open the CdbRecordset object, and is automatically removed when you close it.

You can create as many CdbRecordset object variables as needed. Different CdbRecordset objects can access the same tables, queries, and fields without conflicting.

To refer to a CdbRecordset object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Recordsets[0]

Recordsets["name"]

Note You can open a CdbRecordset object from the same data source or database more than once, creating duplicate names in the Recordsets collection. You should assign CdbRecordset objects to object variables and refer to them by variable name.


Recordset Object Summary (DAO)

CdbRecordset Object Summary

A Cdbecordset object contains these collections, methods, and properties.

Legend:

Feature available in both Microsoft Jet and ODBCDirect workspaces.
Feature available in Microsoft Jet workspaces only.
Feature available in ODBCDirect workspaces only.

Collections

Fields (default)
Properties

Methods

The following table lists all of the CdbRecordset methods, and shows which CdbRecordset type supports each method, and whether the method is available in either a Microsoft Jet or ODBCDirect workspace, or both.

Method | Table | Dynaset | Snapshot | Forward-Only | Dynamic
AddNew |  |  | * |  |
Cancel |  |  |  |  |
CancelUpdate |  |  | * |  |
Clone |  |  |  |  |
Close |  |  |  |  |
CopyQueryDef |  |  |  |  |
Delete |  |  | * |  |
Edit |  |  | * |  |
FillCache |  |  |  |  |
FindFirst |  |  |  |  |
FindLast |  |  |  |  |
FindNext |  |  |  |  |
FindPrevious |  |  |  |  |
GetField |  |  |  |  |
GetRows |  |  |  |  |
GetRowsEx |  |  |  |  |
Move |  |  |  | ** |
MoveFirst |  |  |  |  |
MoveLast |  |  |  |  |
MoveNext |  |  |  |  |
MovePrevious |  |  |  |  |
NextRecordset |  |  |  |  |
OpenRecordset |  |  |  |  |
Requery |  |  |  |  |
Seek |  |  |  |  |
SetField |  |  |  |  |
Update |  |  | * |  |

* In an ODBCDirect workspace, a snapshot-type CdbRecordset may be updatable, depending on the ODBC driver. The AddNew, Edit, Delete, Update, and CancelUpdate methods are only available on ODBCDirect snapshot-type CdbRecordset objects if the ODBC driver supports updatable snapshots.

** Used only with forward moves that don't use a bookmark offset.

Properties

The following table indicates which properties apply to each type of CdbRecordset object and whether the property setting is read/write, read-only, or always FALSE in either Microsoft Jet or ODBCDirect databases.

Read-only
Read/write

Property | Table | Dynaset | Snapshot | Forward-Only | Dynamic
AbsolutePosition |  |  |  |  |
BatchCollisionCount |  |  |  |  |
BatchCollisions |  |  |  |  |
BatchSize |  |  |  |  |
BOF |  |  |  |  |
Bookmark |  |  |  |  |
Bookmarkable |  |  |  |  |
CacheSize |  | for Microsoft Jet workspaces |  |  |
 |  | for ODBCDirect workspaces |  |  |
CacheStart |  |  |  |  |
Connection |  |  |  |  |
DateCreated |  |  |  |  |
EditMode |  |  |  |  |
EOF |  |  |  |  |
Filter |  |  |  |  |
Index |  |  |  |  |
LastModified |  |  | * |  |
LastUpdated |  |  |  |  |
LockEdits |  | for Microsoft Jet workspaces | for Microsoft Jet workspaces |  |
 |  | for ODBCDirect workspaces | for ODBCDirect workspaces |  |
Name |  |  |  |  |
NoMatch |  |  |  |  |
PercentPosition |  |  |  |  |
RecordCount |  |  |  |  |
RecordStatus |  |  |  |  |
Restartable | False |  |  |  |
Sort |  |  |  |  |
StillExecuting |  |  |  |  |
Transactions |  |  | Always False | Always False |
Type |  |  |  |  |
Updatable |  |  | Always False in Microsoft Jet workspaces | Always False in Microsoft Jet workspaces |
 |  |  | in ODBCDirect workspaces * | in ODBCDirect workspaces * |
UpdateOptions |  |  |  |  |
ValidationRule |  |  |  |  |
ValidationText |  |  |  |  |

*In an ODBCDirect workspace, a snapshot-type CdbRecordset may be updatable, depending on the ODBC driver. The LastModified property is available and the Updatable property is True only on ODBCDirect snapshot-type CdbRecordset objects if the ODBC driver supports updatable snapshots.

Recordsets Collection

A Recordsets collection appears in each CdbConnection and CdbDatabase object and contains this method and this property.

Method

Refresh

Property

Count


Dynamic-Type Recordset Object (DAO)

Dynamic-Type CdbRecordset Object

This CdbRecordset type represents a query result set from one or more base tables in which you can add, change, or delete records from a row-returning query. Further, records that other users add, delete, or edit in the base tables also appear in your CdbRecordset.

This type is only available in ODBCDirect workspaces and corresponds to an ODBC dynamic cursor.


Dynamic-Type Recordset Object Summary (DAO)

Dynamic-Type CdbRecordset Object Summary

A dynamic-type CdbRecordset object contains these collections, methods, and properties. This type of CdbRecordset and its methods and properties are available only in an ODBCDirect workspace.

Collections

Fields (default)
Properties

Methods

AddNew
Cancel
CancelUpdate
Close
Delete
Edit
GetRows
GetRowsEx
Move
MoveFirst
MoveLast
MoveNext
MovePrevious
NextRecordset
Requery
Update

Properties

The following table indicates whether each property setting is read/write, read-only, or always False.

Read-only

Read/write

Properties | Restrictions
AbsolutePosition |
BatchCollisionCount |
BatchCollisions |
BatchSize |
BOF |
Bookmark |
Bookmarkable |
CacheSize |
Connection |
EditMode |
EOF |
LastModified |
LockEdits |
Name |
PercentPosition |
RecordCount |
RecordStatus |
Restartable |
StillExecuting |
Type |
Updatable |
UpdateOptions |


Dynaset-Type Recordset Object (DAO)

Dynaset-Type CdbRecordset Object

A dynaset-type CdbRecordset object is a dynamic set of records that can contain fields from one or more tables or queries in a database and may be updatable. In an ODBCDirect database, a dynaset-type CdbRecordset object corresponds to an ODBC keyset cursor.

Remarks

A dynaset-type CdbRecordset object is a type of CdbRecordset object you can use to manipulate data in an underlying database table or tables.

It differs from a snapshot-type CdbRecordset object because the dynaset stores only the primary key for each record, instead of actual data. As a result, a dynaset is updated with changes made to the source data, while the snapshot is not. Like the table-type Recordset object, a dynaset retrieves the full record only when it's needed for editing or display purposes.

To create a dynaset-type CdbRecordset object, use the OpenRecordset method on an open database, against another dynaset- or snapshot-type CdbRecordset object, on a CdbQueryDef object, or on a CdbTableDef object. (Opening CdbRecordset objects on other CdbRecordset objects or CdbTableDef objects is available only in Microsoft Jet workspaces.)

If you request a dynaset-type CdbRecordset object and the Microsoft Jet database engine can't gain read/write access to the records, the Microsoft Jet database engine may create a read-only, dynaset-type CdbRecordset object.

As users update data, the base tables reflects these changes. Therefore, current data is available to your application when you reposition the current record. In a multiuser database, more than one user can open a dynaset-type CdbRecordset object referring to the same records. Because a dynaset-type CdbRecordset object is dynamic, when one user changes a record, other users have immediate access to the changed data. However, if one user adds a record, other users won’t see the new record until they use the Requery method on the CdbRecordset object. If a user deletes a record, other users are notified when they try to access it.

Records added to the database don't become a part of your dynaset-type CdbRecordset object unless you add them by using the AddNew and Update methods. For example, if you use an action query containing an INSERT INTO SQL statement to add records, the new records aren't included in your dynaset-type CdbRecordset object until you either use the Requery method or you rebuild your CdbRecordset object using the OpenRecordset method.

To maintain data integrity, the Microsoft Jet database engine can lock dynaset- and table-type CdbRecordset objects during Edit (pessimistic locking) or Update operations (optimistic locking) so that only one user can update a particular record at a time. When the Microsoft Jet database engine locks a record, it locks the entire 2K page containing the record.

You can also use optimistic and pessimistic locking with non-ODBC tables. When you access external tables using ODBC through a Microsoft Jet workspace, always use optimistic locking. The LockEdits property and the lockedits parameter of the OpenRecordset method determine the locking conditions during editing.

Not all fields can be updated in all dynaset-type CdbRecordset objects. To determine whether you can update a particular field, check the DataUpdatable property setting of the Field object.

A dynaset-type CdbRecordset object may not be updatable if:

  • There isn't a unique index on the ODBC or Paradox table or tables.

  • The data page is locked by another user.

  • The record has changed since you last read it.

  • The user doesn't have permission.

  • One or more of the tables or fields are read-only.

  • The database is opened as read-only.

  • The CdbRecordset object was either created from multiple tables without a JOIN statement or the query was too complex.

The order of a dynaset-type CdbRecordset object or CdbRecordset data doesn't necessarily follow any specific sequence. If you need to order your data, use an SQL statement with an ORDER BY clause to create the CdbRecordset object. You can also use a WHERE clause to filter the records so that only certain records are added to the CdbRecordset object. Using SQL statements in this way to select a subset of records and order them usually results in faster access to your data than using the Filter and Sort properties.


Dynaset-Type Recordset Object Summary (DAO)

Dynaset-Type CdbRecordset Object Summary

The dynaset-type CdbRecordset object contains these collections, methods, and properties.

Legend:

Feature available in Microsoft Jet workspaces only.
Feature available in ODBCDirect workspaces only.

Collections

Fields (default)
Properties

Methods | Restrictions
AddNew |
Cancel |
CancelUpdate |
Clone |
Close |
CopyQueryDef |
Delete |
Edit |
FillCache |
FindFirst |
FindLast |
FindNext |
FindPrevious |
GetRows |
GetRowsEx
Move |
MoveFirst |
MoveLast |
MoveNext |
MovePrevious |
NextRecordset |
OpenRecordset |
Requery |
Update |

Properties

The following table indicates whether the property setting is read/write, read-only, or only available in either Microsoft Jet or ODBCDirect workspaces.

Read-only

Read/write

Properties | Restrictions
AbsolutePosition |
BatchCollisionCount |
BatchCollisions |
BatchSize |
BOF |
Bookmark |
Bookmarkable |
CacheSize | Microsoft Jet ODBCDirect
CacheStart |
Connection |
EditMode |
EOF |
Filter |
LastModified |
LockEdits |
Name |
NoMatch |
PercentPosition |
RecordCount |
RecordStatus |
Restartable |
Sort |
StillExecuting |
Transactions |
Type |
Updatable |
UpdateOptions |
ValidationRule |
ValidationText |


Forward-Only-Type Recordset Object (DAO)

Forward-Only–Type CdbRecordset Object

This CdbRecordset type is identical to a snapshot except that you can only scroll forward through its records. This improves performance in situations where you only need to make a single pass through a result set.

In an ODBCDirect workspace, this type corresponds to an ODBC forward-only cursor.


Forward-Only-Type Recordset Object Summary (DAO)

Forward-Only–Type CdbRecordset Object Summary

The forward-only–type CdbRecordset object contains these collections, methods, and properties.

Legend:

Feature available in Microsoft Jet workspaces only.
Feature available in ODBCDirect workspaces only.

Collections

Fields (default)
Properties

Methods | Restrictions
AddNew |
Cancel |
CancelUpdate |
Close |
CopyQueryDef |
Delete |
Edit |
GetRows |
GetRowsEx
Move | Only with forward moves that don't use a bookmark offset.
MoveNext |
NextRecordset |
Requery |
Update |

Properties

The following table indicates whether each property setting is read/write, read-only, or always FALSE in either Microsoft Jet or ODBCDirect workspaces.

Read-only

Read/write

Properties | Restrictions
BatchCollisionCount |
BatchCollisions |
BatchSize |
BOF |
Connection |
EOF |
Filter |
Name |
RecordCount |
RecordStatus |
Restartable |
StillExecuting |
Transactions | Always FALSE
Type |
Updatable | FALSE
UpdateOptions |
ValidationRule |
ValidationText |


Snapshot-Type Recordset Object (DAO)

Snapshot-Type CdbRecordset Object

A snapshot-type CdbRecordset object is a static set of records that you can use to examine data in an underlying table or tables. In an ODBCDirect database, a snapshot-type CdbRecordset object corresponds to a static cursor.

Remarks

To create a snapshot-type CdbRecordset object, use the OpenRecordset method on an open database, on another dynaset- or snapshot-type CdbRecordset object, or on a CdbQueryDef object.

A snapshot-type CdbRecordset object can contain fields from one or more tables in a database. In a Microsoft Jet workspace, a snapshot can't be updated. In an ODBCDirect workspace, a snapshot may be updatable, depending on the ODBC driver.

When you create a snapshot-type CdbRecordset object, data values for all fields (except Memo and OLE Object (Long Binary) field data types in .mdb files) are brought into memory. Once loaded, changes made to base table data aren't reflected in the snapshot-type CdbRecordset object data. To reload the snapshot-type CdbRecordset object with current data, use the Requery method or re-execute the OpenRecordset method.

The order of snapshot-type CdbRecordset object data doesn't necessarily follow any specific sequence. To order your data, use an SQL statement with an ORDER BY clause to create the CdbRecordset object. You can also use this technique to filter the records so that only certain records are added to the CdbRecordset object. Using this technique instead of using the Filter or Sort properties or testing each record individually generally results in faster access to your data.

Snapshot-type CdbRecordset objects are generally faster to create and access than dynaset-type CdbRecordset objects because their records are either in memory or stored in TEMP disk space, and the Microsoft Jet database engine doesn't need to lock pages or handle multiuser issues. However, snapshot-type CdbRecordset objects use more resources than dynaset-type CdbRecordset objects because the entire record is downloaded to local memory.


Snapshot-Type Recordset Object Summary (DAO)

Snapshot-Type CdbRecordset Object Summary

The snapshot-type CdbRecordset object contains these collections, methods, and properties.

Legend:

Feature available in Microsoft Jet workspaces only.
Feature available in ODBCDirect workspaces only.

Collections

Fields (default)
Properties

Methods | Restrictions
AddNew | *
Cancel |
CancelUpdate | *
Clone |
Close |
CopyQueryDef |
Delete | *
Edit | *
FindFirst |
FindLast |
FindNext |
FindPrevious |
GetRows |
GetRowsEx
Move |
MoveFirst |
MoveLast |
MoveNext |
MovePrevious |
NextRecordset |
OpenRecordset |
Requery |
Update | *

* In an ODBCDirect workspace, a snapshot-type CdbRecordset may be updatable, depending on the ODBC driver. The AddNew, Edit, Delete, Update, and CancelUpdate methods are only available on ODBCDirect snapshot-type CdbRecordset objects if the ODBC driver supports updatable snapshots.

Properties

The following table indicates whether the property setting is read/write, read-only, or always FALSE in either Microsoft Jet or ODBCDirect workspaces.

Read-only

Read/write

Properties | Restrictions
AbsolutePosition |
BatchCollisionCount |
BatchCollisions |
BatchSize |
BOF |
Bookmark |
Bookmarkable |
CacheSize |
Connection |
EditMode |
EOF |
Filter |
LastModified | *
LockEdits |
Name |
NoMatch | bmc ro.bmp}
PercentPosition |
RecordStatus |
Restartable |
Sort |
StillExecuting | bmc ro.bmp}
Transactions | Always FALSE
Type |
Updatable | Always FALSE in Microsoft Jet workspaces; [image] in ODBCDirect workspaces *
UpdateOptions |
ValidationRule |
ValidationText |

* In an ODBCDirect workspace, a snapshot-type CdbRecordset may be updatable, depending on the ODBC driver. The LastModified property is available, and the Updatable property is True only on ODBCDirect snapshot-type CdbRecordset objects if the ODBC driver supports updatable snapshots.


Table-Type Recordset Object (DAO)

Table-Type CdbRecordset Object

A table-type CdbRecordset object represents a base table you can use to add, change, or delete records from a table. Only the current record is loaded into memory. A predefined index determines the order of the records in the CdbRecordset object (Microsoft Jet workspaces only).

Remarks

To create a table-type CdbRecordset object, use the OpenRecordset method on an open CdbDatabase object.

You can create a table-type CdbRecordset object from a base table of a Microsoft Jet database, but not from an ODBC or linked table. You can use the table-type CdbRecordset object with ISAM databases (like Microsoft Visual FoxPro, dBASE, or Paradox) when you open them directly.

Unlike dynaset- or snapshot-type CdbRecordset objects, the table-type CdbRecordset object can't refer to more than one base table, and you can't create it with an SQL statement that filters or sorts the data. Generally, when you access a table-type CdbRecordset object, you specify one of the predefined indexes for the table, which orders the data returned to your application. If the table doesn't have an index, the data won't necessarily be in a particular order. If necessary, your application can create an index that returns records in a specific order. To choose a specific order for your table-type CdbRecordset object, set the Index property to a valid index.

Also unlike dynaset- or snapshot-type CdbRecordset objects, you don't need to explicitly populate table-type CdbRecordset objects to obtain an accurate value for the RecordCount property.

To maintain data integrity, table-type CdbRecordset objects are locked during the Edit and Update methods operations so that only one user can update a particular record at a time. When the Microsoft Jet database engine locks a record, it locks the entire 2K page containing the record.

Two kinds of locking are used with non-ODBC tables — pessimistic and optimistic. ODBC-accessed tables always use optimistic locking. The LockEdits property determines the locking conditions in effect during editing.


Table-Type Recordset Object Summary (DAO)

Table-Type CdbRecordset Object Summary

A table-type CdbRecordset object contains these collections, methods, and properties. This type of CdbRecordset and its methods and properties are available only in a Microsoft Jet workspace.

Collections

Fields (default)
Properties

Methods

AddNew
CancelUpdate
Clone
Close
Delete
Edit
GetRows
GetRowsEx
Move
MoveFirst
MoveLast
MoveNext
MovePrevious
OpenRecordset
Seek
Update

Properties

The following table indicates whether each property setting is read/write, read-only, or always FALSE.

Read-only

Read/write

Properties | Restrictions
BOF |
Bookmark |
Bookmarkable |
DateCreated |
EditMode |
EOF |
Index |
LastModified |
LastUpdated |
LockEdits |
Name |
NoMatch |
PercentPosition |
RecordCount |
Restartable | Always FALSE
Transactions |
Type |
Updatable |
ValidationRule |
ValidationText |


Relation Object (DAO)

CdbRelation Object

A CdbRelation object represents a relationship between fields in tables or queries (Microsoft Jet databases only).

Remarks

You can use the CdbRelation object to create new relationships and examine existing relationships in your database.

Using a CdbRelation object and its properties, you can:

  • Specify an enforced relationship between fields in base tables (but not a relationship that involves a query or a linked table).

  • Establish unenforced relationships between any type of table or query — native or linked.

  • Use the Name property to refer to the relationship between the fields in the referenced primary table and the referencing foreign table.

  • Use the Attributes property to determine whether the relationship between fields in the table is one-to-one or one-to-many and how to enforce referential integrity.

  • Use the Attributes property to determine whether the Microsoft Jet database engine can perform cascading update and cascading delete operations on primary and foreign tables.

  • Use the Attributes property to determine whether the relationship between fields in the table is left join or right join.

  • Use the Name property of all CdbField objects in the Fields collection of a CdbRelation object to set or return the names of the fields in the primary key of the referenced table, or the ForeignName property settings of the CdbField objects to set or return the names of the fields in the foreign key of the referencing table.

If you make changes that violate the relationships established for the database, a trappable error occurs. If you request cascading update or cascading delete operations, the Microsoft Jet database engine also modifies the primary or foreign key tables to enforce the relationships you establish.

For example, the Northwind database contains a relationship between an Orders table and a Customers table. The CustomerID field of the Customers table is the primary key, and the CustomerID field of the Orders table is the foreign key. For Microsoft Jet to accept a new record in the Orders table, it searches the Customers table for a match on the CustomerID field of the Orders table. If Microsoft Jet doesn't find a match, it doesn't accept the new record and a trappable error occurs.

When you enforce referential integrity, a unique index must already exist for the key field of the referenced table. The Microsoft Jet database engine automatically creates an index with the Foreign property set to act as the foreign key in the referencing table.

To create a new CdbRelation object, use the CreateRelation method. To refer to a CdbRelation object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Relations[0]

Relations["name"]

CdbRelation Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbRelation(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbRelation(const CdbRelation &);

Type | Description
const CdbRelation & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbRelation(DAORelation *prl,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAORelation * | prl | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Relations Collection (DAO)

Relations Collection

A Relations collection contains stored CdbRelation objects of a CdbDatabase object (Microsoft Jet databases only).

Remarks

You can use the CdbRelation object to create new relationships and examine existing relationships in your database. To add a CdbRelation object to the Relations collection, first create it with the CreateRelation method, and then append it to the Relations collection with the Append method. This will save the CdbRelation object when you close the CdbDatabase object. To remove a CdbRelation object from the collection, use the Delete method.

To refer to a CdbRelation object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Relations[0]

Relations["name"]


TableDef Object (DAO)

CdbTableDef Object

A CdbTableDef object represents the stored definition of a base table or a linked table (Microsoft Jet workspaces only).

Remarks

You manipulate a table definition using a CdbTableDef object and its methods and properties. For example, you can:

  • Examine the field and index structure of any local, linked, or external table in a database.

  • Use the Connect and SourceTableName properties to set or return information about linked tables, and use the RefreshLink method to update connections to linked tables.

  • Use the ValidationRule and ValidationText properties to set or return validation conditions.

  • Use the OpenRecordset method to create a table-, dynaset-, dynamic -, snapshot-, or forward-only–type CdbRecordset object, based on the table definition.

For base tables, the RecordCount property contains the number of records in the specified database table. For linked tables, the RecordCount property setting is always -1.

To create a new CdbTableDef object, use the CreateTableDef method.

To add a field to a table

  1. Make sure any CdbRecordset objects based on the table are all closed.

  2. Use the CreateField method to create a CdbField object variable and set its properties.

  3. Use the Append method to add the CdbField object to the Fields collection of the CdbTableDef object.

You can delete a CdbField object from a TableDefs collection if it doesn't have any indexes assigned to it, but you will lose the field's data.

To create a table that is ready for new records in a database

  4. Use the CreateTableDef method to create a CdbTableDef object.

  5. Set its properties.

  6. For each field in the table, use the CreateField method to create a CdbField object variable and set its properties.

  7. Use the Append method to add the fields to the Fields collection of the CdbTableDef object.

  8. Use the Append method to add the new CdbTableDef object to the TableDefs collection of the Database object.

A linked table is connected to the database by the SourceTableName and Connect properties of the CdbTableDef object.

To link a table to a database

  9. Use the CreateTableDef method to create a CdbTableDef object.

  10. Set its Connect and SourceTableName properties (and optionally, its Attributes property).

  11. Use the Append method to add it to the TableDefs collection of a Database.

To refer to a CdbTableDef object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

TableDefs[0]

TableDefs["name"]

CdbTableDef Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbTableDef(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbTableDef(const CdbTableDef &);

Type | Description
const CdbTableDef & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbTableDef(DAOTableDef *ptd,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAOTableDef * | ptd | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


TableDefs Collection (DAO)

TableDefs Collection

A TableDefs collection contains all stored CdbTableDef objects in a database (Microsoft Jet workspaces only).

Remarks

You manipulate a table definition using a CdbTableDef object and its methods and properties.

The default collection of a Database object is the TableDefs collection.

To refer to a CdbTableDef object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

TableDefs[0]

TableDefs["name"]


User Object (DAO)

CdbUser Object

A CdbUser object represents a user account that has access permissions when a CdbWorkspace object operates as a secure workgroup (Microsoft Jet workspaces only).

Remarks

You use CdbUser objects to establish and enforce access permissions for the CdbDocument objects that represent databases, tables, and queries. Also, if you know the properties of a specific CdbUser object, you can create a new CdbWorkspace object that has the same access permissions as the CdbUser object.

You can append an existing CdbUser object to the Users collection of a CdbGroup object to give a user account the access permissions for that CdbGroup object. Alternatively, you can append the CdbGroup object to the Groups collection in a CdbUser object to establish membership of the user account in that group. If you use a Users or Groups collection other than the one to which you just appended an object, you may need to use the Refresh method.

With the properties of a CdbUser object, you can:

  • Use the Name property to return the name of an existing user. You can't return the PID and Password properties of an existing CdbUser object.

  • Use the Name, PID, and Password properties of a newly created, unappended CdbUser object to establish the identity of that CdbUser object. If you don't set the Password property, it's set to a zero-length string ("").

The Microsoft Jet database engine predefines two CdbUser objects named Admin and Guest. The user Admin is a member of both of the CdbGroup objects named Admins and Users; the user Guest is a member only of the CdbGroup object named Guests.

To create a new CdbUser object, use the CreateUser method.

To refer to a CdbUser object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Users[0]

Users["name"]

CdbUser Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbUser(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbUser(const CdbUser &);

Type | Description
const CdbUser & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbUser(DAOUser *pusr,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAOUser * | pusr | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Users Collection (DAO)

Users Collection

A Users collection contains all stored CdbUser objects of a CdbWorkspace or CdbGroup object (Microsoft Jet workspaces only).

Remarks

You can append an existing CdbUser object to the Users collection of a CdbGroup object to give a user account the access permissions for that CdbGroup object. Alternatively, you can append the CdbGroup object to the Groups collection in a CdbUser object to establish membership of the user account in that group. If you use a Users or Groups collection other than the one to which you just appended an object, you may need to use the Refresh method.

The Microsoft Jet database engine predefines two CdbUser objects named Admin and Guest. The user Admin is a member of both of the CdbGroup objects named Admins and Users; the user Guest is a member only of the CdbGroup object named Guests.

To refer to a CdbUser object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Users[0]

Users["name"]


Workspace Object (DAO)

CdbWorkspace Object

A CdbWorkspace object defines a named session for a user. It contains open databases and provides mechanisms for simultaneous transactions and, in Microsoft Jet workspaces, secure workgroup support. It also controls whether you are going through the Microsoft Jet database engine or ODBCDirect to access external data.

Remarks

A CdbWorkspace is a non-persistent object that defines how your application interacts with data — either by using the Microsoft Jet database engine or ODBCDirect. Use the CdbWorkspace object to manage the current session or to start an additional session. In a session, you can open multiple databases or connections and manage transactions. For example, you can:

  • Use the Name, UserName, and Type properties to establish a named session. The session creates a scope in which you can open multiple databases and conduct one instance of nested transactions.

  • Use the Close method to terminate a session.

  • Use the OpenDatabase method to open one or more existing databases on a CdbWorkspace.

  • Use the BeginTrans, CommitTrans, and Rollback methods to manage nested transaction processing within a CdbWorkspace and use several CdbWorkspace objects to conduct multiple, simultaneous, and overlapping transactions.

Further, using a Microsoft Jet database, you can establish security based on user names and passwords:

  • Use the Groups and Users collections to establish group and user access permissions to objects in the CdbWorkspace.

  • Use the IsolateODBCTrans property to isolate multiple transactions that involve the same Microsoft Jet-connected ODBC database.

When you first refer to or use a CdbWorkspace object, you automatically create the default workspace, DBEngine.Workspaces(0). The settings of the Name and UserName properties of the default workspace are "#Default Workspace#" and "Admin," respectively. If security is enabled, the UserName property setting is the name of the user who logged on.

To establish an ODBCDirect CdbWorkspace object, and thereby avoid loading the Microsoft Jet database engine into memory, set the DBEngine object's DefaultType property to dbUseODBC, or set the type argument of the CreateWorkspace method to dbUseODBC.

When you use transactions, all databases in the specified CdbWorkspace are affected — even if multiple Database objects are opened in the CdbWorkspace. For example, you use a BeginTrans method, update several records in a database, and then delete records in another database. If you then use the Rollback method, both the update and delete operations are canceled and rolled back. You can create additional CdbWorkspace objects to manage transactions independently across Database objects.

You can create CdbWorkspace objects with the CreateWorkspace method. After you create a new CdbWorkspace object, you must append it to the Workspaces collection if you need to refer to it from the Workspaces collection.

You can use a newly created CdbWorkspace object without appending it to the Workspaces collection. However, you must refer to it by the object variable to which you have assigned it.

To refer to a CdbWorkspace object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Workspaces[0]

Workspaces["name"]

CdbWorkspace Constructor Syntax

Use any one of the following three constructors. The qualifier 'CONSTRUCTOR' in the syntax models is provided to help readability. It has no syntactic value.

CONSTRUCTORCdbWorkspace(VOID);

This constructor creates an instance of the class. There are no parameters.

CONSTRUCTORCdbWorkspace(const CdbWorkspace &);

Type | Description
const CdbWorkspace & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

CONSTRUCTORCdbWorkspace(DAOWorkspace *pwrk,

BOOL bAddRef = FALSE);

Type | Argument | Description
DAOWorkspace * | pwrk | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to enable you to easily create a DAO class object if you have access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object, but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Workspaces Collection (DAO)

Workspaces Collection

A Workspaces collection contains all active, unhidden CdbWorkspace objects of the DBEngine object. (Hidden CdbWorkspace objects are not appended to the collection and referenced by the variable to which they are assigned.)

Remarks

Use the CdbWorkspace object to manage the current session or to start an additional session.

When you first refer to or use a CdbWorkspace object, you automatically create the default workspace, DBEngine.Workspaces(0). The settings of the Name and UserName properties of the default workspace are "#Default Workspace#" and "Admin," respectively. If security is enabled, the UserName property setting is the name of the user who logged on.

You can create new CdbWorkspace objects with the CreateWorkspace method. After you create a new CdbWorkspace object, you must append it to the Workspaces collection if you need to refer to it from the Workspaces collection. You can, however, use a newly created CdbWorkspace object without appending it to the Workspaces collection.

To refer to a CdbWorkspace object in a collection by its ordinal number or by its Name property setting, use either of the following syntax forms:

Workspaces[0]

Workspaces["name"]


DAO Methods by Object

This reference groups all DAO methods by object. To see whether a particular method is available for Microsoft Jet or ODBC workspaces, check the Help topic for that method.

CdbConnection

CdbContainer — no methods

CdbDatabase

CdbDBEngine

CdbDocument

CdbError — no methods

CdbField

CdbGroup

CdbIndex

 CdbParameter — no methods

CdbProperty — no methods

CdbQueryDef

CdbRecordset

CdbRelation

CdbTableDef

CdbUser

CdbWorkspace


DAO Methods for Microsoft Jet Workspaces

This reference lists alphabetically all DAO methods available for Microsoft Jet workspaces (ISAM database files).

A-C

AddNew

Append

AppendChunk

BeginTrans

CancelUpdate

Clone

Close

CommitTrans

CompactDatabase

CopyQueryDef

 CreateDatabase

CreateField

CreateGroup

CreateIndex

CreateProperty

CreateQueryDef

CreateRelation

CreateTableDef

CreateUser

CreateWorkspace

D-M

Delete

Edit

Execute

FieldSize

FillCache

FindFirst

FindLast

FindNext

FindPrevious

GetChunk

 GetField

GetRows

GetRowsEx

Idle

MakeReplica

Move

MoveFirst

MoveLast

MoveNext

MovePrevious

N-Z

NewPassword

OpenDatabase

OpenRecordset

PopulatePartial

Refresh

RefreshLink

RegisterDatabase

RepairDatabase

 Requery

Rollback

Seek

SetField

SetOption

Start

Synchronize

Update


DAO Methods for ODBCDirect Workspaces

This reference alphabetically lists all DAO methods available for ODBCDirect workspaces.

A-F

AddNew

Append

AppendChunk

BeginTrans

Cancel

CancelUpdate

Clone

Close

 CommitTrans

CreateQueryDef

CreateWorkspace

Delete

Edit

Execute

FieldSize

G-Z

GetChunk

GetField

GetRows

GetRowsEx

Move

MoveFirst

MoveLast

MoveNext

MovePrevious

NextRecordset

 OpenConnection

OpenDatabase

OpenRecordset

Refresh

RegisterDatabase

Requery

Rollback

SetField

Update


AddNew Method (DAO)

AddNew Method

Creates a new record for an updatable CdbRecordset object.

Syntax

VOIDAddNew(VOID);

Remarks

Use the AddNew method to create and add a new record in the CdbRecordset object named by recordset. This method sets the fields to default values, and if no default values are specified, it sets the fields to Null (the default values specified for a table-type CdbRecordset).

After you modify the new record, use the Update method to save the changes and add the record to the CdbRecordset. No changes occur in the database until you use the Update method.

Caution If you issue an AddNew and then perform any operation that moves to another record, but without using Update, your changes are lost without warning. In addition, if you close the CdbRecordset or end the procedure that declares the CdbRecordset or its CdbDatabase object, the new record is discarded without warning.

Note When you use AddNew in a Microsoft Jet workspace and the database engine has to create a new page to hold the current record, page locking is pessimistic. If the new record fits in an existing page, page locking is optimistic.

If you have not moved to the last record of your CdbRecordset, records added to base tables by other processes may be included if they are positioned beyond the current record. If you add a record to your own CdbRecordset, however, the record is visible in the CdbRecordset and included in the underlying table where it becomes visible to any new CdbRecordset objects.

The position of the new record depends on the type of CdbRecordset:

  • In a dynaset-type CdbRecordset object, records are inserted at the end of the CdbRecordset, regardless of any sorting or ordering rules that were in effect when the CdbRecordset was opened.

  • In a table-type CdbRecordset object whose CdbIndex property has been set, records are returned in their proper place in the sort order. If you have not set the CdbIndex property, new records are returned at the end of the CdbRecordset.

The record that was current before you used AddNew remains current. If you want to make the new record current, you can set the Bookmark property to the bookmark identified by the LastModified property setting.

Note To add, edit, or delete a record, there must be a unique index on the record in the underlying data source. If not, a "Permission denied" error will occur on the AddNew, Delete, or Edit method call in a Microsoft Jet workspace, or an "Invalid argument" error will occur on the Update call in an ODBCDirect workspace.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rst;
...
rst.AddNew();      // Create an empty recordset.
...            // Set the values of the recordset.
//fields.
rst.Update()      // Save your changes.
rst.Close();      // Close the recordset.


Append Method (DAO)

Append Method

Adds a new DAO object to a collection.

Syntax

VOID collection.Append( class& object );

The Append method syntax has these parts.

Part | Description
collection | An object variable that represents any collection that can accept new objects (for limitations, see the table at the end of this topic).
class& | Reference to an object variable to be appended, which must be of the same class as the elements of collection.

Remarks

You can use the Append method to add a new table to a database, add a field to a table, and add a field to an index.

The appended object becomes a persistent object, stored on disk, until you delete it by using the Delete method. If collection is a CdbWorkspaces collection (which is stored only in memory), the object is active until you remove it by using the Close method.

The addition of a new object occurs immediately, but you should use the Refresh method on any other collections that may be affected by changes to the database structure.

If the object you are appending isn’t complete (such as when you haven’t appended any CdbField objects to a Fields collection of an CdbIndex object before it’s appended to an Indexes collection) or if the properties set in one or more subordinate objects are incorrect, using the Append method causes an error. For example, if you haven’t specified a field type and then try to append the CdbField object to the Fields collection in a CdbTableDef object, using the Append method triggers a run-time error.

The following table lists some limitations of the Append method. The object in the first column is an object containing the collection in the second column. The third column indicates whether you can append an object to that collection (for example, you can never append a CdbContainer object to the Containers collection of a CdbDatabase object).

Object | Collection | Can you append new objects?
CdbDBEngine | Workspaces | Yes
CdbDBEngine | Errors | No. New Error objects are automatically appended when they occur.
CdbWorkspace | Connections | No. Using the OpenConnection method automatically appends new objects.
CdbWorkspace | Databases | No. Using the OpenDatabase method automatically appends new objects.
CdbWorkspace | Groups | Yes
CdbWorkspace | Users | Yes
CdbConnection | QueryDefs | No. Using the CreateQueryDef method automatically appends new objects.
CdbConnection | Recordsets | No. Using the OpenRecordset method automatically appends new objects.
CdbDatabase | Containers | No
CdbDatabase | QueryDefs | Only when the CdbQueryDef object is a new, unappended object created with no name. See the CreateQueryDef method for details.
CdbDatabase | Recordsets | No. Using the OpenRecordset method automatically appends new objects.
CdbDatabase | Relations | Yes
CdbDatabase | TableDefs | Yes
CdbGroup | Users | Yes
CdbUser | Groups | Yes
CdbContainer | Documents | No
CdbQueryDef | Fields | No
CdbQueryDef | Parameters | No
CdbRecordset | Fields | No
CdbRelation | Fields | Yes
CdbTableDef | Fields | Only when the Updatable property of the CdbTableDef object is set to True, or when the CdbTableDef object is unappended.
CdbTableDef | Indexes | Only when the Updatable property of the CdbTableDef is set to True, or when the CdbTableDef object is unappended.
CdbIndex | Fields | Only when the CdbIndex object is a new, unappended object.
CdbDatabase, CdbField, CdbIndex, CdbQueryDef, CdbTableDef | Properties | Only when the CdbDatabase, CdbField, CdbIndex, CdbQueryDef, or CdbTableDef object is in a Microsoft Jet workspace.
CdbDBEngine, CdbParameter, CdbRecordset, CdbWorkspace | Properties | No


AppendChunk Method (DAO)

AppendChunk Method

Appends data from a string expression to a Memo or Long Binary CdbField object in a CdbRecordset.

Syntax

VOIDAppendChunk(LPVARIANT pv );

Parameters

Type | Argument | Description
LPVARIANT | pv | A pointer to a variant whose value will be appended to the Fields collection.

Remarks

You can use the AppendChunk and GetChunk methods to access subsets of data in a Memo or Long Binary field.

You can also use these methods to conserve string space when you work with Memo and Long Binary fields. Certain operations (copying, for example) involve temporary strings. If string space is limited, you may need to work with chunks of a field instead of the entire field.

If there is no current record when you use AppendChunk, an error occurs.

Notes

  • The initial AppendChunk operation (after an Edit or AddNew call) will simply place the data in the field, overwriting any existing data. Subsequent AppendChunk calls within the same Edit or AddNew session will then add to the existing data.

  • In an ODBCDirect workspace, unless you first edit another field in the current record, using AppendChunk will fail (though no error occurs) while you are in Edit mode.

  • In an ODBCDirect workspace, after you use AppendChunk on a field, you cannot read or write that field in an assignment statement until you move off the current record and then return to it. You can do this by using the MoveNext and MovePrevious methods.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rs;
CdbField         fld;
COleVariant      vVal("abcdefghijklmnop", VT_BSTRT);
...                     // Initialize recordset, etc.
fld = rs.Fields[0];         // Get a field.
fld.AppendChunk(&vVal);    // Append the chunk.


BeginTrans, CommitTrans, Rollback Methods (DAO)

BeginTrans, CommitTrans, Rollback Methods

The transaction methods manage transaction processing during a session defined by a CdbWorkspace object as follows:

  • BeginTrans begins a new transaction.

  • CommitTrans ends the current transaction and saves the changes.

  • Rollback ends the current transaction and restores the databases in the CdbWorkspace object to the state they were in when the current transaction began.

Syntax

VOIDBeginTrans(VOID);

VOIDCommitTrans (LONG lOptions = -1);

VOIDRollback(VOID);

Parameters

Type | Example | Description
LONG | IOptions =-1 | Optional. Use the dbForceOSFlush constant to flush all updates to disk, instead of caching them.

Remarks

You use these methods with a CdbWorkspace object when you want to treat a series of changes made to the databases in a session as one unit.

Typically, you use transactions to maintain the integrity of your data when you must both update records in two or more tables and ensure changes are completed (committed) in all tables or none at all (rolled back). For example, if you transfer money from one account to another, you might subtract an amount from one and add the amount to another. If either update fails, the accounts no longer balance. Use the BeginTrans method before updating the first record, and then, if any subsequent update fails, you can use the Rollback method to undo all of the updates. Use the CommitTrans method after you successfully update the last record.

In a Microsoft Jet workspace, you can include the dbForceOSFlush constant with CommitTrans. This forces the database engine to immediately flush all updates to disk, instead of caching them temporarily. Without using this option, a user could get control back immediately after the application program calls CommitTrans, turn the computer off, and not have the data written to disk. While using this option may affect your application’s performance, it is useful in situations where the computer could be shut off before cached updates are saved to disk.

Caution Within one CdbWorkspace object, transactions are always global to the CdbWorkspace and aren't limited to only one CdbConnection or CdbDatabase object. If you perform operations on more than one connection or database within a CdbWorkspace transaction, resolving the transaction (that is, using the CommitTrans or Rollback method) affects all operations on all connections and databases within that workspace.

After you use CommitTrans, you can't undo changes made during that transaction unless the transaction is nested within another transaction that is itself rolled back. If you nest transactions, you must resolve the current transaction before you can resolve a transaction at a higher level of nesting.

If you want to have simultaneous transactions with overlapping, non-nested scopes, you can create additional CdbWorkspace objects to contain the concurrent transactions.

If you close a CdbWorkspace object without resolving any pending transactions, the transactions are automatically rolled back.

If you use the CommitTrans or Rollback method without first using the BeginTrans method, an error occurs.

Some ISAM databases used in a Microsoft Jet workspace may not support transactions, in which case the CdbTransactions property of the CdbDatabase object or CdbRecordset object is False. To make sure the database supports transactions, check the value of the CdbTransactions property of the CdbDatabase object before using the BeginTrans method. If you are using a CdbRecordset object based on more than one database, check the CdbTransactions property of the CdbRecordset object. If a CdbRecordset is based entirely on Microsoft Jet tables, you can always use transactions. CdbRecordset objects based on tables created by other database products, however, may not support transactions. For example, you can't use transactions in a CdbRecordset based on a Paradox table. In this case, the CdbTransactions property is False. If the CdbDatabase or CdbRecordset doesn't support transactions, the methods are ignored and no error occurs.

You can't nest transactions if you are accessing ODBC data sources through the Microsoft Jet database engine.

Notes

  • You can often improve the performance of your application by breaking operations that require disk access into transaction blocks. This buffers your operations and may significantly reduce the number of times a disk is accessed.

  • In a Microsoft Jet workspace, transactions are logged in a file kept in the directory specified by the TEMP environment variable on the workstation. If the transaction log file exhausts the available storage on your TEMP drive, the database engine triggers a run-time error. At this point, if you use CommitTrans, an indeterminate number of operations are committed, but the remaining uncompleted operations are lost, and the operation has to be restarted. Using a Rollback method releases the transaction log and rolls back all operations in the transaction.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbWorkspace      ws;
BOOL            error;
...
ws.BeginTrans();      // Start working.
...                  // Make some changes.
if (error)
   ws.Rollback();   // Reject changes.
else
   ws.CommitTrans();    // Accept changes.
ws.Close();         // Close the workspace.


Cancel Method (DAO)

Cancel Method

Cancels execution of a pending asynchronous method call (ODBCDirect workspaces only).

Syntax

VOIDCancel(VOID);

Remarks

Use the Cancel method to terminate execution of an asynchronous Execute, MoveLast, OpenConnection, or OpenRecordset method call (that is, the method was invoked with the dbRunAsync option). Cancel will return a run-time error if dbRunAsync was not used in the method you are trying to terminate.

The following table shows what task is terminated when you use the Cancel method on a particular type of object.

If you call Cancel from a | This asynchronous method is terminated
CdbConnection | Execute or OpenConnection
CdbQueryDef | Execute
CdbRecordset | MoveLast or OpenRecordset

An error will occur if, following a Cancel method call, you try to reference the object that would have been created by an asynchronous OpenConnection or OpenRecordset call (that is, the CdbConnection or CdbRecordset object from which you called the Cancel method).

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine         dben(...,dbUseODBC);
CdbWorkspace      wrkMain;
CdbConnect         conMain;

wrkMain = dben.CreateWorkspace("ODBCWorkspace",
               _T("admin"), _T(""), dbUseODBC);
// Open the connection asynchronously.
conMain = wrkMain.OpenConnection("Publishers",
               (dbDriverNoPrompt   dbRunAsync),
               FALSE,
               _T("ODBC;DATABASE=pubs;UID=sa;PWD=;DSN=Publishers"));
// Wait a few seconds...
// If the connection has not been made, quit.
if (conMain.StillExecuting())
   conMain.Cancel();
else
   {      // Use the Connection object conMain.
   ...
   conMain.Close();
   }
wrkMain.Close();


CancelUpdate Method (DAO)

CancelUpdate Method

Cancels any pending updates for a Recordset object.

Syntax

VOIDCancelUpdate(short sType = dbUpdateRegular);

Parameters

Type | Example | Description
SHORT | sType = dbUpdateRegular | Optional. A constant indicating the type of update (ODBCDirect workspaces only).

Settings

You can use the following values for the sType argument only if batch updating is enabled.

Constant | Description
dbUpdateRegular | Default. Cancels pending changes that aren’t cached.
DbUpdateBatch | Cancels pending changes in the update cache.

Remarks

You can use the CancelUpdate method to cancel any pending updates resulting from an Edit or AddNew operation. For example, if a user invokes the Edit or AddNew method and hasn't yet invoked the Update method, CancelUpdate cancels any changes made after Edit or AddNew was invoked.

Check the EditMode property of the CdbRecordset to determine if there is a pending operation that can be canceled.

Note Using the CancelUpdate method has the same effect as moving to another record without using the Update method, except that the current record doesn't change, and various properties, such as BOF and EOF, aren't updated.

Usage

#include <afxole.h>
#include <dbdao.h>
...
BOOL            bOK = TRUE;
CdbRecordset      rst;
...
rst.AddNew();            // Begin to add a record
if (bOK)               // Is it OK to add a record?
   rst.Update();         // yes: Complete the addition
else                  // no: Abort the addition
   rst.CancelUpdate(dbUpdateRegular);


Clone Method (DAO)

Clone Method

Creates a duplicate CdbRecordset object that refers to the original CdbRecordset object.

Syntax

CdbRecordsetClone(VOID);

Remarks

Clone returns an instance of CdbRecordset.

Remarks

Use the Clone method to create multiple, duplicate CdbRecordset objects. Each CdbRecordset can have its own current record. Using Clone by itself doesn't change the data in the objects or in their underlying structures. When you use the Clone method, you can share bookmarks between two or more CdbRecordset objects because their bookmarks are interchangeable.

You can use the Clone method when you want to perform an operation on a CdbRecordset that requires multiple current records. This is faster and more efficient than opening a second CdbRecordset. When you create a CdbRecordset with the Clone method, it initially lacks a current record. To make a record current before you use the CdbRecordset clone, you must set the Bookmark property or use one of the Move methods, one of the Find methods, or the Seek method.

Using the Close method on either the original or duplicate object doesn't affect the other object. For example, using Close on the original CdbRecordset doesn't close the clone.

Notes

  • Closing a clone CdbRecordset within a pending transaction will cause an implicit Rollback operation.

  • When you clone a table-type CdbRecordset object in a Microsoft Jet workspace, the Index property setting is not cloned on the new copy of the CdbRecordset. You must copy the Index property setting manually.

  • You can use the Clone method with forward-only–type CdbRecordset objects only in an ODBCDirect workspace.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rstOriginal, rstNew;
...   // Open the original recordset.
      // Make a duplicate of it.
rstNew = rstOriginal.Clone();


Close Method (DAO)

Close Method

Closes an open DAO object.

Syntax

VOIDClose(VOID);

Remarks

Closing an open object removes it from the collection to which it's appended. Any attempt to close the default workspace is ignored.

If the CdbConnection, CdbDatabase, CdbRecordset, or CdbWorkspace object is already closed when you use Close, a run-time error occurs.

Caution If you exit a procedure that declares CdbConnection, CdbDatabase, or CdbRecordset objects, those objects are closed, all pending transactions are rolled back, and any pending edits to your data are lost.

If you try to close a CdbConnection or CdbDatabase object while it has any open CdbRecordset objects, the CdbRecordset objects will be closed and any pending updates or edits will be canceled. Similarly, if you try to close a CdbWorkspace object while it has any open CdbConnection or CdbDatabase objects, those CdbConnection and CdbDatabase objects will be closed, which will close their CdbRecordset objects.

Using the Close method on either an original or cloned CdbRecordset object doesn't affect the other CdbRecordset object.

To remove objects from updatable collections other than the Connections, Databases, Recordsets, and Workspaces collections, use the Delete method on those collections. You can't add a new member to the Containers, Documents, and Errors collections.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDatabase   db;
db = dben.OpenDatabase(_T("MyDatabase.mbd"));
...               // Do some work.
db.Close();        // Close the database.


CompactDatabase Method (DAO)

CompactDatabase Method

Copies and compacts a closed database, and gives you the option of changing its version, collating order, and encryption. (Microsoft Jet workspaces only).

Syntax

VOIDCompactDatabase(LPCTSTR pstrOldDatabase,

LPCTSTR pstrNewDatabase,

LPCTSTR pstrDstConnect = NULL,

LONG lOptions = -1,

LPCTSTR pstrSrcConnect = NULL);

Parameters

Type | Argument | Description
LPCTSTR | pstrOldDatabase | A pointer to a string that identifies an existing, closed database. It can be a full path and file name, such as "C:\db1.mdb". If the file name has an extension, you must specify it. If your network supports it, you can also specify a network path, such as "\\server1\share1\dir1\db1.mdb".
LPCTSTR | pstrNewDatabase | A pointer to a string that is the file name (and path) of the compacted database that you are creating. You can also specify a network path. You can't use the pstrNewDatabase argument to specify the same database file as pstrOldDatabase.
LPCTSTR | pstrDstConnect | Optional. A pointer to a string composed of zero or more parameters separated by semicolons. This parameter is used to pass additional information to the destination database as needed. For example, collating order is specified here.
LONG | Ioptions | Optional. A constant or combination of constants that indicates one or more options. The options specify the version of its data format and whether the new compacted database should be encrypted.
LPCTSTR | pstrSrcConnect | Optional. A pointer to a string composed of zero or more parameters separated by semicolons. This parameter is used to pass additional information from the source as needed.

Settings

You can concatenate one of the following constants in the pstrDstConnect argument to specify the CollatingOrder for string comparisons of text in the compacted database.

Constant | Collating order
dbLangGeneral | English, German, French, Portuguese, Italian, and Modern Spanish
dbLangArabic | Arabic
dbLangChineseSimplified | Simplified Chinese
dbLangChineseTraditional | Traditional Chinese
dbLangCyrillic | Russian
dbLangCzech | Czech
dbLangDutch | Dutch
dbLangGreek | Greek
dbLangHebrew | Hebrew
dbLangHungarian | Hungarian
dbLangIcelandic | Icelandic
dbLangJapanese | Japanese
dbLangKorean | Korean
dbLangNordic | Nordic languages (Microsoft Jet database engine version 1.0 only)
dbLangNorwDan | Norwegian and Danish
dbLangPolish | Polish
dbLangSlovenian | Slovenian
dbLangSpanish | Traditional Spanish
dbLangSwedFin | Swedish and Finnish
dbLangThai | Thai
dbLangTurkish | Turkish

You can use one of the following constants in the lOptions argument to specify whether to encrypt or to decrypt the database while it's compacted.

Constant | Description
dbEncrypt | Encrypt the database while compacting.
DbDecrypt | Decrypt the database while compacting.

If you omit an encryption constant or if you include both dbDecrypt and dbEncrypt, pstrNewDatabase will have the same encryption as pstrOldDatabase.

You can use one of the following constants in the lOptions argument to specify the version of the data format for the compacted database. This constant affects only the version of the data format of pstrNewDatabase and doesn't affect the version of any Microsoft Access-defined objects, such as forms and reports.

Constant | Description
dbVersion10 | Creates a database that uses the Microsoft Jet database engine version 1.0 file format while compacting.
dbVersion11 | Creates a database that uses the Microsoft Jet database engine version 1.1 file format while compacting.
dbVersion20 | Creates a database that uses the Microsoft Jet database engine version 2.0 file format while compacting.
dbVersion30 | Creates a database that uses the Microsoft Jet database engine version 3.0 file format (compatible with version 3.5) while compacting.

You can specify only one version constant. If you omit a version constant, pstrNewDatabase will have the same version as pstrOldDatabase. You can compact pstrNewDatabase only to a version that is the same or later than that of pstrOldDatabase.

Remarks

As you change data in a database, the database file can become fragmented and use more disk space than is necessary. Periodically, you can use the CompactDatabase method to compact your database to defragment the database file. The compacted database is usually smaller and often runs faster. You can also change the collating order, the encryption, or the version of the data format while you copy and compact the database.

You must close pstrOldDatabase before you compact it. In a multiuser environment, other users can't have pstrOldDatabase open while you are compacting it. If pstrOldDatabase isn't closed or isn't available for exclusive use, an error occurs.

Because CompactDatabase creates a copy of the database, you must have enough disk space for both the original and the duplicate databases. The compact operation fails if there isn't enough disk space available. The pstrNewDatabase duplicate database doesn't have to be on the same disk as pstrOldDatabase. After successfully compacting a database, you can delete the pstrOldDatabase file and rename the compacted pstrNewDatabase file to the original file name.

The CompactDatabase method copies all the data and the security permission settings from the database specified by pstrOldDatabase to the database specified by pstrNewDatabase.

If you use CompactDatabase to convert a version 1.x database to version 2.5 or 3.x, only applications using version Microsoft Jet 2.5 or 3.x can open the converted database.

Note In an ODBCDirect workspace, using the CompactDatabase method doesn't return an error, but instead loads the Microsoft Jet database engine into memory.

Caution Because the CompactDatabase method doesn't convert Microsoft Access objects, you shouldn't use CompactDatabase to convert a database containing such objects.

Usage

#include <afxole.h>
#include <dbdao.h>
...
CdbDBEngine   dben;
...
dben.CompactDatabase(   _T("Northwind.mdb"), _T("Nwind2.mdb"),
                     dbLangGeneral, // This is really a string.
                     dbVersion30);


CopyQueryDef Method (DAO)

CopyQueryDef Method

Returns a CdbQueryDef object that is a copy of the QueryDef used to create the CdbRecordset object represented by the recordset placeholder (Microsoft Jet workspaces only).

Syntax

CdbQueryDefCopyQueryDef(VOID);

Remarks

You can use the CopyQueryDef method to create a new CdbQueryDef that is a duplicate of the CdbQueryDef used to create the CdbRecordset.

If a CdbQueryDef wasn't used to create this CdbRecordset, an error occurs. You must first open a CdbRecordset with the OpenRecordset method before using the CopyQueryDef method.

This method is useful when you create a CdbRecordset object from a CdbQueryDef, and pass the CdbRecordset to a function, and the function must re-create the SQL equivalent of the query, for example, to modify it in some way.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
CdbRecordset       rst;
CdbDatabase      dbs;
CdbQueryDef      qd;
CString         strSQL = _T("SELECT * FROM PARTS");
...
dbs = dben.OpenDatabase(_T("Northwind.mdb"));
   // Get a recordset based on a query.
rst = dbs.OpenRecordset(strSQL);
   // Get a copy of the query that built the recordset.
qd = rst.CopyQueryDef();     // Copy the queryDef


CreateDatabase Method (DAO)

CreateDatabase Method

Creates a new CdbDatabase object, saves the database to disk, and returns an opened CdbDatabase object (Microsoft Jet workspaces only).

Syntax

CdbDatabaseCreateDatabase(LPCTSTR pstrName,

LPCTSTR pstrConnect,

LONG lOptions = -1);

Parameters

Type | Argument | Description
LPCTSTR | pstrName | A pointer to a string up to 255 characters long that is the name of the database file that you're creating. It can be the full path and file name, such as "C:\db1.mdb". If you don't supply a file name extension, .mdb is appended. If your network supports it, you can also specify a network path, such as "\\server1\share1\dir1\db1". You can only create .mdb database files with this method.
LPCTSTR pstrConnect A pointer to a string that specifies various connection information, including the collating order for text strings and a password.

You can create a password for the new Database object by concatenating the password string (starting with ";pwd=") with a constant, for example:

dbLangSpanish & ";pwd=Password"

If you want to use the default collating order, but specify a password, simply enter a password string for this argument:

";pwd=Password"
LONG | lOptions | Optional. A constant or combination of constants that indicates one or more options. See Settings for details.

Settings

You can concatenate one of the following constants in the pstrConnect argument to specify the CollatingOrder for string comparisons of text in the database.

Constant | Collating order
dbLangGeneral | English, German, French, Portuguese, Italian, and Modern Spanish
dbLangArabic | Arabic
dbLangChineseSimplified | Simplified Chinese
dbLangChineseTraditional | Traditional Chinese
dbLangCyrillic | Russian
dbLangCzech | Czech
dbLangDutch | Dutch
dbLangGreek | Greek
dbLangHebrew | Hebrew
dbLangHungarian | Hungarian
dbLangIcelandic | Icelandic
dbLangJapanese | Japanese
dbLangKorean | Korean
dbLangNordic | Nordic languages (Microsoft Jet database engine version 1.0 only)
dbLangNorwDan | Norwegian and Danish
dbLangPolish | Polish
dbLangSlovenian | Slovenian
dbLangSpanish | Traditional Spanish
dbLangSwedFin | Swedish and Finnish
dbLangThai | Thai
dbLangTurkish | Turkish

You can use one or more of the following constants in the lOptions argument to specify which version the data format should have and whether or not to encrypt the database.

Constant | Description
dbEncrypt | Creates an encrypted database.
DbVersion10 | Creates a database that uses the Microsoft Jet database engine version 1.0 file format.
DbVersion11 | Creates a database that uses the Microsoft Jet database engine version 1.1 file format.
DbVersion20 | Creates a database that uses the Microsoft Jet database engine version 2.0 file format.
DbVersion30 | (Default) Creates a database that uses the Microsoft Jet database engine version 3.0 file format (compatible with version 3.5).

If you omit the encryption constant, CreateDatabase creates an un-encrypted database. You can specify only one version constant. If you omit a version constant, CreateDatabase creates a database that uses the Microsoft Jet database engine version 3.0 file format.

Remarks

Use the CreateDatabase method to create and open a new, empty database, and return the CdbDatabase object. You must complete its structure and content by using additional DAO objects. If you want to make a partial or complete copy of an existing database, you can use the CompactDatabase method to make a copy that you can customize.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
CdbWorkspace      wrkDefault;
CdbDatabase      dbsNew;

wrkDefault = dben.Workspaces(0L);
/* Create a new encrypted database with the specified
   (dbLangGeneral) collating order.
*/
dbsNew = wrkDefault.CreateDatabase(_T("NewDB.mdb"),
                                 dbLangGeneral, dbEncrypt);
...
dbsNew.Close();


CreateField Method (DAO)

CreateField Method

Creates a new CdbField object (Microsoft Jet workspaces only).

Syntax

CdbFieldCreateField(LPCTSTR pstrName = NULL,

LONG lType = -1,

LONG lSize = -1);

Parameters

Type | Example | Description
LPCTSTR | pstrName = NULL | Optional. A pointer to a string that uniquely names the new CdbField object. See the Name property for details on valid CdbField names.
LONG | lType = -1 | Optional. An integer that determines the data type of the new CdbField object. See the Type property for valid data types.
LONG | lSize = -1 | Optional. An integer that indicates the maximum size, in bytes, of a CdbField object that contains text. See the Size property for valid size values. This argument is ignored for numeric and fixed-width fields.

Remarks

You can use the CreateField method to create a new field, as well as specify the name, data type, and size of the field. If you omit one or more of the optional parts when you use CreateField, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the new object, you can alter some but not all of its property settings. See the individual property topics for more details.

The lType and lSize arguments apply only to CdbField objects in a CdbTableDef object. These arguments are ignored when a CdbField object is associated with a CdbIndex or CdbRelation object.

If pstrName refers to an object that is already a member of the collection, a run-time error occurs when you use the Append method.

To remove a CdbField object from a Fields collection, use the Delete method on the collection. You can't delete a CdbField object from a CdbTableDef object's Fields collection after you create an index that references the field.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbTableDef   td;
...
td.CreateField(_T("CarModel"), dbText, 30);


CreateGroup Method (DAO)

CreateGroup Method

Creates a new CdbGroup object (Microsoft Jet workspaces only).

Syntax

CdbGroupCreateGroup(LPCTSTR pstrName = NULL,

LPCTSTR pstrPID = NULL);

Parameters

Type | Argument | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new CdbGroup object. See the Name property for details on valid CdbGroup names.
LPCTSTR | pstrPID | Optional. A pointer to a string containing the PID of a group account. The identifier must contain from 4 to 20 alphanumeric characters. See the PID property for more information on valid personal identifiers.

Remarks

You can use the CreateGroup method to create a new CdbGroup object for a CdbUser or CdbWorkspace. If you omit one or both of the optional parts when you use CreateGroup, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can alter some but not all of its property settings. See the individual property topics for more details.

If pstrName refers to an object that is already a member of the collection, a run-time error occurs when you use the Append method.

To remove a CdbGroup object from a collection, use the Delete method on the Groups collection.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine       dben;
CdbWorkspace      ws;
CdbUser            usr;
CdbGroup         grp;
...
ws = dben.Workspaces[0L];
usr = ws.CreateUser(_T("JohnDoe"), _T("Accountant"), _T("ACCT001"));
grp = ws.CreateGroup(_T("Accountants"), _T("DEPT_01_99"));
grp.Users.Append(usr);
usr.Groups.Append(grp);


CreateIndex Method (DAO)

CreateIndex Method

Creates a new CdbIndex object (Microsoft Jet workspaces only).

Syntax

CdbIndexCreateIndex(LPCTSTR pstrName = NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName = NULL | Optional. A pointer to a string that uniquely names the new CdbIndex object. See the Name property for details on valid CdbIndex names.

Remarks

You can use the CreateIndex method to create a new CdbIndex object for a CdbTableDef object. If you omit the optional name part when you use CreateIndex, you can use an appropriate assignment statement to set or reset the Name property before you append the new object to a collection. After you append the object, you may or may not be able to set its Name property, depending on the type of object that contains the Indexes collection. See the Name property topic for more details.

If pstrName refers to an object that is already a member of the collection, a run-time error occurs when you use the Append method.

To remove a CdbIndex object from a collection, use the Delete method on the collection.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbIndex      idx;
CdbTableDef      td;
...                           // Initialize td, etc.
idx = td.CreateIndex(   _T("CarPartsIdx"));


CreateProperty Method (DAO)

CreateProperty Method

Creates a new user-defined CdbProperty object (Microsoft Jet workspaces only).

Syntax

CdbPropertyCreateProperty(LPCTSTR pstrName = NULL,

LONG lType = -1,

LPVARIANT pvValue = NULL,

BOOL bDDL = FALSE);

Parameters

Type | Argument | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new CdbProperty object. See the Name property for details on valid property names.
LONG | lType | Optional. A constant that defines the data type of the new CdbProperty object. See the Type property for valid data types.
LPVARIANT | pvValue | Optional. A pointer to a Variant containing the initial property value. See the Value property for details.
BOOL | bDDL = FALSE | Optional. A Boolean that indicates whether or not the CdbProperty is a DDL object. If TRUE, users can't change or delete this CdbProperty object unless they have dbSecWriteDef permission.

Remarks

You can create a user-defined CdbProperty object only in the Properties collection of an object that is persistent.

If you omit one or more of the optional parts when you use CreateProperty, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can alter some but not all of its property settings. See the Name, Type, and Value property topics for more details.

If name refers to an object that is already a member of the collection, a run-time error occurs when you use the Append method.

To remove a user-defined CdbProperty object from the collection, use the Delete method on the Properties collection. You can't delete built-in properties.

Note If you omit the DDL argument, it defaults to False (non-DDL). Because no corresponding DDL property is exposed, you must delete and re-create a CdbProperty object you want to change from DDL to non-DDL.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDatabase      dbs;
CdbProperty      prop;
COleVariant      vVal(FALSE, VT_BOOL);

// Initialize dbs, etc.
// Create a property that says whether this database contains
// information that must be reported quarterly.

dbs  = dben.OpenDatabase(...);
prop = dbs.CreateProperty(_T("QuarterlyReportRequired"),                dbBoolean, &vVal, FALSE);
dbs.Properties.Append( prop );  // Append property.


CreateQueryDef Method (DAO)

CreateQueryDef Method

Creates a new CdbQueryDef object in a specified CdbConnection or CdbDatabase object.

Syntax

CdbQueryDefCreateQueryDef(LPCTSTR pstrName = NULL,

LPCTSTR pstrSQL = NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new CdbQueryDef.
LPCTSTR | pstrSQL | Optional. A pointer to a string that is an SQL statement defining the CdbQueryDef. If you omit this argument, you can define the CdbQueryDef by setting its SQL property before or after you append it to a collection.

Remarks

In a Microsoft Jet workspace, if you provide anything other than a zero-length string for the name when you create a CdbQueryDef, the resulting CdbQueryDef object is automatically appended to the QueryDefs collection. In an ODBCDirect workspace, CdbQueryDef objects are always temporary.

In an ODBCDirect workspace, the pstrSQL argument can specify an SQL statement or a Microsoft SQL Server stored procedure and its parameters.

If the object specified by pstrName is already a member of the QueryDefs collection, a run-time error occurs. You can create a temporary CdbQueryDef by using a zero-length string for the pstrName argument when you execute the CreateQueryDef method. You can also accomplish this by setting the Name property of a newly created CdbQueryDef to a zero-length string (""). Temporary CdbQueryDef objects are useful if you want to repeatedly use dynamic SQL statements without having to create any new permanent objects in the QueryDefs collection. You can't append a temporary CdbQueryDef to any collection because a zero-length string isn't a valid name for a permanent CdbQueryDef object. You can always set the Name and SQL properties of the newly created CdbQueryDef object and subsequently append the CdbQueryDef to the QueryDefs collection.

To run the SQL statement in a CdbQueryDef object, use the Execute or OpenRecordset method.

Using a QueryDef object is the preferred way to perform SQL pass-through queries with ODBC databases.

To remove a CdbQueryDef object from a QueryDefs collection in a Microsoft Jet database, use the Delete method on the collection. For an ODBCDirect database, use the Close method on the CdbQueryDef object.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDatabase   db;
CdbQueryDef   qd1;
...                        // Initialize db, etc.
qd1 = CreateQueryDef(_T("QD_PARTS"), _T("SELECT * FROM PARTS"));


CreateRelation Method (DAO)

CreateRelation Method

Creates a new CdbRelation object (Microsoft Jet workspaces only).

Syntax

CdbRelationCreateRelation(LPCTSTR pstrName = NULL,

LPCTSTR pstrTable = NULL,

LPCTSTR pstrForeign = NULL,

LONG lAttributes = -1);

Parameters

Type | Argument | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new CdbRelation object. See the Name property for details on valid relation names.
LPCTSTR | pstrTable | Optional. A pointer to a string that names the primary table in the relation. If the table doesn't exist before you append the CdbRelation object, a run-time error occurs.
LPCTSTR | pstrForeign | Optional. A pointer to a string that names the foreign table in the relation. If the table doesn't exist before you append the CdbRelation object, a run-time error occurs.
LONG | lAttributes | Optional. A constant or combination of constants that contains information about the relationship type. See the Attributes property for details.

Remarks

The Relation object provides information to the Microsoft Jet database engine about the relationship between fields in two CdbTableDef or CdbQueryDef objects. You can implement referential integrity by using the Attributes property.

If you omit one or more of the optional arguments when you use the CreateRelation method, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can't alter any of its property settings. See the individual property topics for more details.

Before you can use the Append method on a CdbRelation object, you must append the appropriate CdbField objects to define the primary and foreign key relationship tables.

If pstrName refers to an object that is already a member of the collection or if the CdbField object names provided in the subordinate Fields collection are invalid, a run-time error occurs when you use the Append method.

You can't establish or maintain a relationship between a replicated table and a local table.

To remove a CdbRelation object from the Relations collection, use the Delete method on the collection.

Usage

#include <afxole.h>
#include <dbdao.h>
...
CdbDBEngine   dben;
CdbDatabase   dbs;
CdbRelation   rel;

dbs = dben.OpenDatabase(_T("Acme.mdb"));
rel = dbs.CreateRelation(_T("EmpSecurity"),_T("Employees"),
                            _T("SocialSecurity", dbRelationUnique);


CreateTableDef Method (DAO)

CreateTableDef Method

Creates a new CdbTableDef object (Microsoft Jet workspaces only).

Syntax

CdbTableDefCreateTableDef(LPCTSTR pstrName = NULL,

LONG lAttributes = -1,

LPCTSTR pstrSource = NULL,

LPCTSTR pstrConnect = NULL);

Parameters

Type | Argument | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new CdbTableDef object. See the Name property for details on valid CdbTableDef names.
LONG | lAttributes | Optional. A constant or combination of constants that indicates one or more characteristics of the new CdbTableDef object. See the Attributes property for more information.
LPCTSTR | pstrSource | Optional. A pointer to a string containing the name of a table in an external database that is the original source of the data. The source string becomes the SourceTableName property setting of the new CdbTableDef object.
LPCTSTR | pstrConnect | Optional. A pointer to a string containing information about the source of an open database, a database used in a pass-through query, or a linked table. See the Connect property for more information about valid connection strings.

Remarks

If you omit one or more of the optional arguments when you use the CreateTableDef method, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can alter some but not all of its properties. See the individual property topics for more details.

If pstrName refers to an object that is already a member of the collection, or you specify an invalid property in the CdbTableDef or CdbField object you're appending, a run-time error occurs when you use the Append method. Also, you can't append a CdbTableDef object to the TableDefs collection until you define at least one CdbField for the CdbTableDef object.

To remove a CdbTableDef object from the TableDefs collection, use the Delete method on the collection.

Usage

#include <afxole.h>
#include <dbdao.h>
   // Create a new TableDef object in the Biblio.mdb database.
CdbDbenine    dben;
CdbTableDef    tdfTitle;
CdbField    fldComments;
CdbDatabase    dbsBiblio;

dbsBiblio = dben.Workspaces[0L].OpenDatabase(_T("Biblio.mdb"));
   // Create new TableDef.
tdfTitle = dbsBiblio.CreateTableDef(_T("Title Detail"));
   // Create and append field to tdfTitle.
fldComments = tdfTitle.CreateField(_T("Comments"), dbMemo);
tdfTitle.Fields.Append(fldComments);
   // Append TableDef to TableDefs collection.
dbsBiblio.TableDefs.Append(tdfTitle);


CreateUser Method (DAO)

CreateUser Method

Creates a new CdbUser object (Microsoft Jet workspaces only).

Syntax

CdbUserCreateUser(LPCTSTR pstrName = NULL,

LPCTSTR pstrPID = NULL,

LPCTSTR pstrPassword = NULL);

Parameters

Type | Argument | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new CdbUser object. See the Name property for details on valid CdbUser names.
LPCTSTR | pstrPID | Optional. A pointer to a string containing the personal identifier (PID) of a user account. The PID must contain from 4 to 20 alphanumeric characters. See the PID property for more information on valid personal identifiers.
LPCTSTR | pstrPassword | Optional. A pointer to a string containing the password for the new CdbUser object. The password can be up to 14 characters long and can include any characters except the ASCII character 0 ( null ). See the Password property for more information on valid passwords.

Remarks

If you omit one or more of the optional arguments when you use the CreateUser method, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can alter some, but not all, of its property settings. See the PID, Name, and Password property topics for more details.

If pstrName refers to an object that is already a member of the collection, a run-time error occurs when you use the Append method.

To remove a CdbUser object from the Users collection, use the Delete method on the collection.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine       dben;
CdbWorkspace      ws;
CdbUser               usr;
CdbGroup         grp;
...
ws = dben.Workspaces[0L];
usr = ws.CreateUser(_T("JohnDoe"), _T("Accountant"), _T("ACCT001"));
grp = ws.CreateGroup(_T("Accountants"), _T("DEPT_01_99"));
grp.Users.Append(usr);
usr.Groups.Append(grp);


CreateWorkspace Method (DAO)

CreateWorkspace Method

Creates a new CdbWorkspace object.

Syntax

CdbWorkspaceCreateWorkspace(LPCTSTR pstrName,

LPCTSTR pstrUser,

LPCTSTR pstrPassword,

LONG lType = dbUseJet);

Parameters

Type | Argument | Description
LPCTSTR | pstrName | A pointer to a string that uniquely names the new CdbWorkspace object. See the Name property for details on valid workspace names.
LPCTSTR | pstrUser | A pointer to a string that identifies the owner of the new CdbWorkspace object. See the UserName property for more information.
LPCTSTR | pstrPassword | A pointer to a string containing the password for the new CdbWorkspace object. The password can be up to 14 characters long and can include any characters except ASCII character 0 ( null ). See the Password property for more information on valid passwords.
LONG | Itype | An integer that specifies whether the type of the workspace should be Microsoft Jet or ODBC. The default is a Microsoft Jet workspace.

Settings

You can use the following constants for lType.

Constant | Description
dbUseJet | Creates a Microsoft Jet workspace.
dbUseODBC | Creates an ODBCDirect workspace.

Remarks

Once you use the CreateWorkspace method to create a new CdbWorkspace object, a CdbWorkspace session is started, and you can refer to the CdbWorkspace object in your application.

CdbWorkspace objects aren't permanent and you can't save them to disk. Once you create a CdbWorkspace object, you can't alter any of its property settings, except for the Name property, which you can modify before appending the CdbWorkspace object to the Workspaces collection.

You don't have to append the new CdbWorkspace object to a collection before you can use it. You append a newly created CdbWorkspace object only if you need to refer to it through the Workspaces collection.

The lType option determines whether the new CdbWorkspace is a Microsoft Jet or ODBCDirect workspace. If you set lType to CdbUseODBC and you haven't already created any Microsoft Jet workspaces, then the Microsoft Jet database engine will not be loaded into memory, and all activity will occur with the ODBC data source subsequently identified in a CdbConnection object. If you omit lType, the DefaultType property of CdbDBEngine will determine which type of data source the CdbWorkspace is connected to. You can have both Microsoft Jet and ODBCDirect workspaces open at the same time.

To remove a CdbWorkspace object from the Workspaces collection, close all open databases and connections and then use the Close method on the CdbWorkspace object.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbDBEngine      dben;
CdbWorkspace      ws;
ws = dben.CreateWorkspace(   _T("MyWorkSpace"), _T("IOwnIt"),                               _T("MyPassword"), dbUseJet);


Delete Method (DAO)

Delete Method

  • Recordset objects deletes the current record in an updatable Recordset object. For ODBCDirect workspaces, the type of driver determines whether Recordset objects are updatable and therefore support the Delete method.

  • Collections deletes a persistent object from a collection.

Syntax: Recordset

VOIDDelete(VOID);

Syntax: Collections

VOID collection.Delete (LPCTSTR pstr );

The collections Delete method syntax has these parts.

Part | Description
collection | An object variable that represents any collection that can accept new objects (for limitations, see the table at the end of this topic).
pstr | A pointer to a string which names the element of the collection to be deleted.

Remarks

You can use the Delete method to delete a current record from a CdbRecordset or a member from a collection, such as a stored table from a database, a stored field from a table, or a stored index from a table.

Recordsets

A Recordset must contain a current record before you use Delete; otherwise, a run-time error occurs.

In an updatable Recordset object, Delete removes the current record and makes it inaccessible. Although you can't edit or use the deleted record, it remains current. Once you move to another record, however, you can't make the deleted record current again. Subsequent references to a deleted record in a Recordset are invalid and produce an error.

You can undo a record deletion if you use transactions and the Rollback method.

If the base table is the primary table in a cascading delete relationship, deleting the current record may also delete one or more records in a foreign table.

Note To add, edit, or delete a record, there must be a unique index on the record in the underlying data source. If not, a "Permission denied" error will occur on the AddNew, Delete, or Edit method call in a Microsoft Jet workspace, or an "Invalid argument" error will occur on the Update method call in an ODBCDirect workspace.

Collections

You can use the Delete method to delete a persistent object. However, if the collection is a Databases, Recordsets, or Workspaces collection (each of which is stored only in memory), you can remove an open or active object only by closing that object with the Close method.

The deletion of a stored object occurs immediately, but you should use the Refresh method on any other collections that may be affected by changes to the database structure.

When you delete a CdbTableDef object from the TableDefs collection, you delete the table definition and the data in the table.

The following table lists some limitations of the Delete method. The object in the first column contains the collection in the second column. The third column indicates if you can delete an object from that collection (for example, you can never delete a CdbContainer object from the Containers collection of a CdbDatabase object).

Object | Collection | Can you use the Delete method?
CdbDBEngine | Workspaces | No. Closing the objects deletes them.
CdbDBEngine | Errors | No
CdbWorkspace | Connections | No. Closing the objects deletes them.
CdbWorkspace | Databases | No. Closing the objects deletes them.
CdbWorkspace | Groups | Yes
CdbWorkspace | Users | Yes
CdbConnection | QueryDefs | No
CdbConnection | Recordsets | No. Closing the objects deletes them.
CdbDatabase | Containers | No
CdbDatabase | QueryDefs | Yes
CdbDatabase | Recordsets | No. Closing the objects deletes them.
CdbDatabase | Relations | Yes
CdbDatabase | TableDefs | Yes
CdbGroup | Users | Yes
CdbUser | Groups | Yes
CdbContainer | Documents | No
CdbQueryDef | Fields | No
CdbQueryDef | Parameters | No
CdbRecordset | Fields | No
CdbRelation | Fields | Only when the CdbRelation object is a new, unappended object.
CdbTableDef | Fields | Only when the CdbTableDef object is new and hasn’t been appended to the database, or when the Updatable property of the CdbTableDef is set to True.
CdbTableDef | Indexes | Only when the CdbTableDef object is new and hasn’t been appended to the database, or when the Updatable property of the CdbTableDef is set to True.
CdbIndex | Fields | Only when the CdbIndex object is new and hasn’t been appended to the database.
CdbDatabase, CdbField, CdbIndex, CdbQueryDef, CdbTableDef | Properties | Only when the property is user-defined.
CdbDBEngine, CdbParameter, CdbRecordset, Workspace | Properties | No

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rst;
...
rst.MoveLast();         // Make the last record the current record.
rst.Delete();            // Delete the current record.
rst.Close();            // Close the recordset.


Edit Method (DAO)

Edit Method

Copies the current record from an updatable CdbRecordset object to the copy buffer for subsequent editing.

Syntax

VOIDEdit(VOID);

Remarks

Once you use the Edit method, changes made to the current record's fields are copied to the copy buffer. After you make the desired changes to the record, use the Update method to save your changes.

The current record remains current after you use Edit.

Caution If you edit a record and then perform any operation that moves to another record, without first using Update, your changes are lost without warning. In addition, if you close the CdbRecordset or end the procedure which declares the CdbRecordset or the parent CdbDatabase or CdbConnection object, your edited record is discarded without warning.

Using Edit produces an error if:

  • There is no current record.

  • The CdbConnection, CdbDatabase, or CdbRecordset object was opened as read-only.

  • No fields in the record are updatable.

  • The CdbDatabase or CdbRecordset was opened for exclusive use by another user (Microsoft Jet workspace).

  • Another user has locked the page containing your record (Microsoft Jet workspace).

In a Microsoft Jet workspace, when the CdbRecordset object's LockEdits property setting is True (pessimistically locked) in a multiuser environment, the record remains locked from the time Edit is used until the update is complete. If the LockEdits property setting is False (optimistically locked), the record is locked and compared with the pre-edited record just before it's updated in the database. If the record has changed since you used the Edit method, the Update operation fails with a run-time error if you use OpenRecordset without specifying dbSeeChanges. By default, Microsoft Jet-connected ODBC and installable ISAM databases always use optimistic locking.

In an ODBCDirect workspace, once you edit and use Update to update a record’s primary key field, you can no longer edit fields in that record until you close the Recordset, and then retrieve the record again in a subsequent query.

Note To add, edit, or delete a record, there must be a unique index on the record in the underlying data source. If not, a "Permission denied" error will occur on the AddNew, Delete, or Edit method call in a Microsoft Jet workspace, or an "Invalid argument" error will occur on the Update call in an ODBCDirect workspace.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rst;
...               // Open the recordset.
rst.Edit();         // Edit the current record.
...               // Make changes to the record.
rst.Update();      // Save the change.
...
rst.Close();         // Close the recordset.


Execute Method (DAO)

Execute Method

Runs an action query or executes an SQL statement on a specified CdbConnection or CdbDatabase object.

Syntax: from a CdbConnection or CdbDatabase object

VOIDExecute(LPCTSTR pstrQuery,

LONG lOptions = -1);

Syntax: from a CdbQueryDef object

VOIDExecute(LONG lOptions = -1);

Parameters

Type | Argument | Description
LPCTSTR | pstrQuery | A pointer to a string that is an SQL statement.
LONG | lOptions | Optional. A constant or combination of constants that determines the data integrity characteristics of the query, as specified in Remarks.

Settings

You can use the following constants for IOptions.

Constant | Description
dbDenyWrite | Denies write permission to other users (Microsoft Jet workspaces only).
DbInconsistent | (Default) Executes inconsistent updates (Microsoft Jet workspaces only).
DbConsistent | Executes consistent updates (Microsoft Jet workspaces only).
DbSQLPassThrough | Executes an SQL pass-through query. Setting this option passes the SQL statement to an ODBC database for processing (Microsoft Jet workspaces only).
DbFailOnError | Rolls back updates if an error occurs (Microsoft Jet workspaces only).
DbSeeChanges | Generates a run-time error if another user is changing data you are editing (Microsoft Jet workspaces only).
DbRunAsync | Executes the query asynchronously (ODBCDirect Connection and QueryDef objects only).
DbExecDirect | Executes the statement without first calling SQLPrepare ODBC API function (ODBCDirect Connection and QueryDef objects only).

Constant | Description
dbDenyWrite | Denies write permission to other users (Microsoft Jet workspaces only).
DbInconsistent | (Default) Executes inconsistent updates (Microsoft Jet workspaces only).
DbConsistent | Executes consistent updates (Microsoft Jet workspaces only).
DbSQLPassThrough | Executes an SQL pass-through query. Setting this option passes the SQL statement to an ODBC database for processing (Microsoft Jet workspaces only).
DbFailOnError | Rolls back updates if an error occurs (Microsoft Jet workspaces only).
DbSeeChanges | Generates a run-time error if another user is changing data you are editing (Microsoft Jet workspaces only).
DbRunAsync | Executes the query asynchronously (ODBCDirect Connection and QueryDef objects only).
DbExecDirect | Executes the statement without first calling SQLPrepare ODBC API function (ODBCDirect Connection and QueryDef objects only).

Note The constants dbConsistent and dbInconsistent are mutually exclusive. You can use one or the other, but not both in a given instance of OpenRecordset. Using both dbConsistent and dbInconsistent causes an error.

Remarks

The Execute method is valid only for action queries. If you use Execute with another type of query, an error occurs. Because an action query doesn't return any records, Execute doesn't return a CdbRecordset. (Executing an SQL pass-through query in an ODBCDirect workspace will not return an error if a CdbRecordset isn't returned.)

Use the RecordsAffected property of the CdbConnection, CdbDatabase, or CdbQueryDef object to determine the number of records affected by the most recent Execute method. For example, RecordsAffected contains the number of records deleted, updated, or inserted when executing an action query. When you use the Execute method to run a query, the RecordsAffected property of the CdbQueryDef object is set to the number of records affected.

In a Microsoft Jet workspace, if you provide a syntactically correct SQL statement and have the appropriate permissions, the Execute method won't fail — even if not a single row can be modified or deleted. Therefore, always use the dbFailOnError option when using the Execute method to run an update or delete query. This option generates a run-time error and rolls back all successful changes if any of the records affected are locked and can't be updated or deleted.

For best performance in a Microsoft Jet workspace, especially in a multiuser environment, nest the Execute method inside a transaction. Use the BeginTrans method on the current CdbWorkspace object, then use the Execute method, and complete the transaction by using the CommitTrans method on the CdbWorkspace. This saves changes on disk and frees any locks placed while the query is running.

In an ODBCDirect workspace, if you include the optional dbRunAsync constant, the query runs asynchronously. To determine whether an asynchronous query is still executing, check the value of the StillExecuting property on the object from which the Execute method was called. To terminate execution of an asynchronous Execute method call, use the Cancel method.

Usage: from a CdbDatabase or CdbConnection object

#include <afxole.h>
#include <dbdao.h>

CdbWorkspace      ws;
CdbDatabase      db;
...                  // Initialize ws, db, etc.

ws.BeginTrans();         // Start working.
db.Execute(_T("SELECT * FROM PARTS"),  dbFailOnError);
                     // Make some changes.
ws.CommitTrans();          // Accept changes.
ws.Close();            // Close the workspace.

Usage: from a CdbQueryDef object

#include <afxole.h>
#include <dbdao.h>

CdbQueryDef       qd;
CdbConnection      conn;
LPCTSTR    lpctsrSQL =
            _T("SELECT SALARY FROM EMPLOYEES ")
            _T("WHERE LASTNAME = 'SMITH'");
...
qd = conn.CreateQueryDef(_T("SALARYDEF"), lpctsrSQL);
qd.Execute(dbFailOnError);


FieldSize Method (DAO)

FieldSize Method

Returns the number of bytes used in the database (rather than in memory) of a Memo or Long Binary CdbField object in the Fields collection of a CdbRecordset object.

Syntax

LONG FieldSize(VOID);

Remarks

You can use FieldSize with the AppendChunk and GetChunk methods to manipulate large fields.

Because the size of a Long Binary or Memo field can exceed 64K, you should assign the value returned by FieldSize to a variable large enough to store a Long variable.

To determine the size of a Field object other than Memo and Long Binary types, use the Size property.

Note In an ODBCDirect workspace, the FieldSize method is not available in the following situations:

  • If the database server or ODBC driver does not support server-side cursors.

  • If you are using the ODBC cursor library (that is, the DefaultCursorDriver property is set to dbUseODBC, or to dbUseDefault when the server does not support server-side cursors).

  • If you are using a cursorless query (that is, the DefaultCursorDriver property is set to dbUseNoCursor).

For example, Microsoft SQL Server version 4.21 does not support server-side cursors, so the FieldSize method is not available.

Usage

#include <afxole.h>
#include <dbdao.h>

LONG            length;
CdbField         fld;
CdbRecordset      rs;
...                  // Initialize as needed
fld = rs.Fields[0L];      // Get the first field
length = fld.FieldSize();   // Get the field size


FillCache Method (DAO)

FillCache Method

Fills all or a part of a local cache for a CdbRecordset object that contains data from a Microsoft Jet-connected ODBC data source (Microsoft Jet-connected ODBC databases only).

Syntax

VOIDFillCache(LONG lRows = -1, CdbBookmark *pbm = NULL);

Parameters

Type | Argument | Description
LONG | lRows | Optional. An integer that specifies the number of rows to store in the cache. If you omit this argument, the value is determined by the CacheSize property setting.
CdbBookmark * | pbm = NULL | Optional. Pointer to a bookmark. The cache is filled starting from the record indicated by this bookmark. If you omit this argument, the cache is filled starting from the record indicated by the CacheStart property.

Remarks

Caching improves the performance of an application that retrieves data from a remote server. A cache is space in local memory that holds the data most recently retrieved from the server; this assumes that the data will probably be requested again while the application is running. When a user requests data, the Microsoft Jet database engine checks the cache for the data first rather than retrieving it from the server, which takes more time. The cache doesn't save data that doesn't come from an ODBC data source.

Rather than waiting for the cache to be filled with records as they are retrieved, you can use the FillCache method to explicitly fill the cache at any time. This is a faster way to fill the cache because FillCache retrieves several records at once instead of one at a time. For example, while you view each screenful of records, your application uses FillCache to retrieve the next screenful of records for viewing.

Any Microsoft Jet-connected ODBC data source that you access with CdbRecordset objects can have a local cache. To create the cache, open a CdbRecordset object from the remote data source, and then set the CacheSize and CacheStart properties of the CdbRecordset.

If lRows and pbm create a range of records that is partially or entirely outside the range of records specified by the CacheSize and CacheStart properties, the portion outside this range is ignored and will not be loaded into the cache.

If FillCache requests more records than the number remaining in the remote data source, Microsoft Jet retrieves only the remaining records, and no error occurs.

Notes

  • Records retrieved from the cache don't reflect concurrent changes that other users made to the source data.

  • FillCache only retrieves records not already cached. To force an update of all the cached data, set the CacheSize property of the CdbRecordset to 0, reset it to the size of the cache you originally requested, and then use FillCache.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBE   ngine      dben(..., dbUseODBC);
CdbDatabase      dbs;
CdbRecordset      rst;
CdbBookmark      book;

dbs = dben.OpenDatabase(_T("ODBC;..."));
rst = dbs.OpenRecordset(..., dbOpenDynaset);
if (rst.Bookmarkable())
{
   // Remember the current record position.
book = rst.GetBookmark();
   // Start the cache from the current position.
rst.SetCacheStart(book);
   // The cache will hold 25 records.
rst.SetCacheSize(25);
rst.FillCache();
   // Do some work...
rst.MoveNext();
   // Get a few more records.
book = rst.GetBookmark();
rst.FillCache(5, &book);
...
}


FindFirst, FindLast, FindNext, FindPrevious Methods (DAO)

FindFirst, FindLast, FindNext, FindPrevious Methods

Locates the first, last, next, or previous record in a dynaset- or snapshot-type Recordset object that satisfies the specified criteria and makes that record the current record (Microsoft Jet workspaces only).

Syntax

VOIDFindFirst( LPCTSTR pstrCriteria );

VOIDFindLast( LPCTSTR pstrCriteria );

VOIDFindNext( LPCTSTR pstrCriteria );

VOIDFindPrevious( LPCTSTR pstrCriteria );

Parameters

Type | Argument | Description
LPCTSTR | pstrCriteria | A pointer to a string expression (like the WHERE clause in an SQL statement without the word WHERE) used to locate the record.

Remarks

If you want to include all the records in your search — not just those that meet a specific condition — use the Move methods to move from record to record. To locate a record in a table-type CdbRecordset, use the Seek method.

If a record matching the criteria isn't located, the current record pointer is unknown, and the NoMatch property is set to True. If recordset contains more than one record that satisfies the criteria, FindFirst locates the first occurrence, FindNext locates the next occurrence, and so on.

Each of the Find methods begins its search from the location and in the direction specified in the following table.

Find method | Begins searching at | Search direction
FindFirst | Beginning of recordset | End of recordset
FindLast | End of recordset | Beginning of recordset
FindNext | Current record | End of recordset
FindPrevious | Current record | Beginning of recordset

When you use the FindLast method, the Microsoft Jet database engine fully populates your CdbRecordset before beginning the search, if this hasn't already happened.

Using one of the Find methods isn't the same as using a Move method, however, which simply makes the first, last, next, or previous record current without specifying a condition. You can follow a Find operation with a Move operation.

Always check the value of the NoMatch property to determine whether the Find operation has succeeded. If the search succeeds, NoMatch is False. If it fails, NoMatch is True and the current record isn't defined. In this case, you must position the current record pointer back to a valid record.

Using the Find methods with Microsoft Jet-connected ODBC-accessed recordsets can be inefficient. You may find that rephrasing your criteria to locate a specific record is faster, especially when working with large recordsets.

In an ODBCDirect workspace, the Find and Seek methods are not available on any type of CdbRecordset object, because executing a Find or Seek through an ODBC connection is not very efficient over the network. Instead, you should design the query (that is, using the source argument to the OpenRecordset method) with an appropriate WHERE clause that restricts the returned records to only those that meet the criteria you would otherwise use in a Find or Seek method.

When working with Microsoft Jet-connected ODBC databases and large dynaset-type CdbRecordset objects, you might discover that using the Find methods or using the Sort or Filter property is slow. To improve performance, use SQL queries with customized ORDER BY or WHERE clauses, parameter queries, or CdbQueryDef objects that retrieve specific indexed records.

Use the U.S. date format (month-day-year) when you search for fields containing dates, even if you're not using the U.S. version of the Microsoft Jet database engine; otherwise, the data may not be found. Use the Microsoft Visual Basic Format function to convert the date. For example:

rstEmployees.FindFirst "HireDate > #" _
   & Format(mydate, 'm-d-yy' ) & "#"

If pstrCriteria is composed of a string concatenated with a non-integer value, and the system parameters specify a non-U.S. decimal character such as a comma (for example, strSQL = "PRICE > " & lngPrice, and lngPrice = 125,50), an error occurs when you try to call the method. This is because during concatenation, the number will be converted to a string using your system's default decimal character, and Microsoft Jet SQL only accepts U.S. decimal characters.

Notes

  • For best performance, the pstrCriteria should be in either the form "field = value" where field is an indexed field in the underlying base table, or "field LIKE prefix" where field is an indexed field in the underlying base table and prefix is a prefix search string (for example, "ART*").

  • In general, for equivalent types of searches, the Seek method provides better performance than the Find methods. This assumes that table-type Recordset objects alone can satisfy your needs.

Usage

#include <afxole.h>
#include <dbdao.h>
...
CdbBookmark         bmHere;
CdbRecordset      rstCustomers;
...
// Save current record position.
bmHere = rstCustomers.GetBookmark();
// Search for a name in the recordset.
rstCustomers.FindFirst(_T("Name = 'Ms. Schmidt'"));
// If not found go back to saved record position.
if (rstCustomers.GetNoMatch())
   rstCustomers.SetBookmark( &bmHere );


GetChunk Method (DAO)

GetChunk Method

Returns all or a portion of the contents of a Memo or Long Binary CdbField object in the Fields collection of a CdbRecordset object.

Syntax

COleVariantGetChunk( LONG lOffset, LONG lBytes );

Parameters

Type | Example | Description
LONG | lOffset | A numeric expression that is the number of bytes to skip before copying begins.
LONG | lBytes | A numeric expression that is the number of bytes you want to return.

Remarks

GetChunk returns COleVariant whose type is set to the type of the accessed field. Use GetChunk to return a portion of the total data value at a time. You can use the AppendChunk method to reassemble the pieces.

If lOffset is 0, GetChunk begins copying from the first byte of the field.

If lBytes is greater than the number of bytes in the field, GetChunk returns the actual number of remaining bytes in the field.

Caution Use a Memo field for text and put binary data only in Long Binary fields. Doing otherwise will cause undesirable results.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rs;
CdbField         fld;
COleVariant      vVal;
...                           // Initialize recordset, etc.
fld = rs.Fields[0];            // Get a field. (Assume it's a 35-byte long string)
vVal = fld.GetChunk(5L, 25L);     // Skip 5 bytes, get the next 25 bytes.


GetField, SetField Methods (dbDAO)

GetField, SetField Methods

GetField returns the value of a CdbField (that is, a table column) in a Recordset. The CdbField is identified by either its name (that is, column name), or its index (that is, cardinal position in the row).

Syntax: GetField

COleVariantGetField( LPCTSTR pstrIndex );

COleVariantGetField( CString &str );

COleVariantGetField( LONG lIndex );

COleVariantGetField( COleVariant &vIndex );

Syntax: SetField

VOIDSetField( LPCTSTR pstrIndex, LPVARIANT pv );

VOIDSetField( CString &str,LPVARIANT pv );

VOIDSetField( LONG lIndex, LPVARIANT pv );

VOIDSetField( COleVariant &vIndex,LPVARIANT pv );

Parameters

Type | Example | Description
LPCTSTR | pstrIndex | A pointer to a string that contains the name of the desired CdbField.
CString & | str | A reference to a CString that contains the name of the desired CdbField.
LONG | lIndex | An integer that is the index of the desired CdbField, starting from the leftmost CdbField and counting from zero.
COleVariant & | vIndex | A reference to a COleVariant with a value that is the index of the desired CdbField, starting from the leftmost CdbField and counting from zero, or a string containing the name of the CdbField.
LPVARIANT | pv | Pointer to a COleVariant whose value will be inserted into the specified CdbField.

Remarks

GetField and SetField are only available in dbDAO. They are provided as a more efficient way of getting or setting the value of a CdbField, other than accessing the CdbRecordset object's Fields collection, then using the GetValue or SetValue properties:

COleVariant vValbyName, vValbyIndex;
vValbyName = recordset.Fields[_T("fieldname")].GetValue();
vValbyIndex = recordset.Fields[index].GetValue();

COleVariant    vName(_T("Smith"), VT_BSTRT),
            vValue(100, VT_I4);
...
recordset.Fields[_T("LastName")].SetValue(&vName);
recordset.Fields[0L].SetValue(&vValue);

Usage: GetField

#include <afxole.h>
#include <dbdao.h>

COleVariant vVal;
   // Initialize a recordset, etc.
   // Get the value of the 'LastName' field.
vVal = recordset.GetField(_T("LastName"));
   // Get the value of the third field.
vVal = recordset.GetField(2L);

Usage: SetField

#include <afxole.h>
#include <dbdao.h>

COleVariant    vName(_T("Smith"), VT_BSTRT),
            vValue(100, VT_I4);
...
recordset.SetField(_T("LastName"), &vName); // set the LastName field
recordset.SetField(0L, &vValue);   // set the first field


GetRows Method (DAO)

GetRows Method

Retrieves multiple rows from a CdbRecordset object.

Syntax

COleVariantGetRows(LONG lRows = -1);

Parameters

Type | Example | Description
LONG | lRows | The number of rows to retrieve. The default is all rows.

Remarks

Use the GetRows method to copy records from a CdbRecordset. GetRows returns a two-dimensional array. The first subscript identifies the field and the second identifies the row number. For example, intField represents the field and intRecord identifies the row number:

avarRecords(intField, intRecord)

To get the first field value in the second row returned, use code like the following:

field1 = avarRecords(0,1)

To get the second field value in the first row, use code like the following:

field2 = avarRecords(1,0)

The avarRecords variable automatically becomes a two-dimensional array when GetRows returns data.

The number of rows that you can retrieve is constrained by the amount of available memory. You shouldn't use GetRows to retrieve an entire table into an array if it is large.

Because GetRows returns all fields of the CdbRecordset into the array, including Memo and Long Binary fields, you might want to use a query that restricts the fields returned.

After you call GetRows, the current record is positioned at the next unread row. That is, GetRows has the same effect on the current record as Move lRows.

If you are trying to retrieve all the rows by using multiple GetRows calls, use the EOF property to be sure that you're at the end of the CdbRecordset. GetRows returns less than the number requested if it's at the end of the CdbRecordset, or if it can't retrieve a row in the range requested. For example, if you're trying to retrieve 10 records, but you can't retrieve the fifth record, GetRows returns four records and makes the fifth record the current record. This will not generate a run-time error. This might occur if another user deletes a record in a dynaset-type CdbRecordset. See the example for a demonstration of how to handle this.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rst;
COleVariant      vRows, vVal;
LONG            lIndex[2], lMax = 10;
HRESULT         hr;

...                           // Open a recordset, etc.
vRows = rst.GetRows(lMax);   // Get 10 rows from the recordset.
lIndex[0] = 0;               // Index the first field.
                           // Index rows 0 through 9.
for (lIndex[1] = 0; lIndex[1] < lMax; lIndex[1]++)
{                           // Get the field.
hr = SafeArrayGetElement(vRows.parray, &lIndex, &vVal);
...                           // Process the field in vVal.
}


GetRowsEx Method (dbDAO)

GetRowsEx Method

The GetRowsEx method retrieves multiple rows and allows you to specify the data types of the fields stored in your application variables.

The GetRowsEx method is a performance improvement by dbDAO and MFC DAO to avoid the necessity to retrieve all data as variants and then convert to native types.

Syntax

LONGGetRowsEx(LPVOID pvBuffer,

LONG cbRow,

LPDAORSETBINDING prb,

LONG cBinding,

LPVOID pvVarBuffer = NULL,

LONG cbVarBuffer = 0,

LONG lRows = -1);

Parameters

Type | Argument | Description
LPVOID | pvBuffer | Pointer to buffer in which to store returned rows.
LONG | cbRow | Length of row in bytes.
LPDAORSETBINDING | prb | Pointer to binding structure.
LONG | cBinding | Number of bindings.
LPVOID | pvVarBuffer = NULL | Optional. Pointer to buffer in which to store variable-length data.
LONG | cbVarBuffer = 0 | Optional. Length in bytes of pvVarBuffer.
LONG | lRows | Optional. Number of rows requested.

Remarks

GetRowsEx is only available in dbDAO.

The DAORSETBINDING structure specifies how data is to be copied from the rows to the memory buffer. A separate binding structure must be filled in for each field retrieved.

Note Each time GetRowsEx retrieves a set of records, it retrieves the last record of the previous set again. For example, if you retrieve five records at a time, GetRowsEx will first retrieve records 1 through 5. The next time it will retrieve records 5 through 10. The time after that, records 10 through 15, and so on. Notice that records 5 and 10 are retrieved twice.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rst;
COleVariant      vRows;
int               n;
LONG            lIndex[2];
HRESULT         hr;
DAORSETBINDING   dsbind;
TCHAR            Buffer[512], VarBuffer[256];
...                        // Open a recordset, fill in binding                            // structure, etc.
vRows = GetRowsEx(&Buffer, cbRow, &dsbind, cBinding,
                  &VarBuffer, sizeof(VarBuffer), 10);
lIndex[0] = 0;            // Index of the 1st field.
lIndex[1] = 1;            // Index of the 2nd row.
                        // Get the field (assume an integer).
hr = SafeArrayGetElement(vRows.parray, &lIndex, &n);


Idle Method (DAO)

Idle Method

Suspends data processing, enabling the Microsoft Jet database engine to complete any pending tasks, such as memory optimization or page timeouts (Microsoft Jet workspaces only).

Syntax

VOIDIdle(LONG lOptions = -1);

Parameters

Type | Argument | Description
LONG | IOptions | Optional. Specify dbRefreshCache to force any pending writes to .mdb files, and refresh memory with the most current data from the .mdb file.

Remarks

The Idle method allows the Microsoft Jet database engine to perform background tasks that may not be up-to-date because of intense data processing. This is often true in multiuser, multitasking environments that don't have enough background processing time to keep all records in a CdbRecordset current.

Usually, read locks are removed and data in local dynaset-type Recordset objects are updated only when no other actions (including mouse movements) occur. If you periodically use the Idle method, Microsoft Jet can catch up on background processing tasks by releasing unneeded read locks.

Specifying the optional dbRefreshCache argument forces any pending writes to .mdb files, and refreshes memory with the most current data from the .mdb file.

You don't need to use this method in single-user environments unless multiple instances of an application are running. The Idle method may increase performance in a multiuser environment because it forces the database engine to write data to disk, releasing locks on memory.

Note You can also release read locks by making operations part of a transaction.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbDBEngine   dben;
dben.Idle(dbRefreshCache);      // Give time to the engine.


MakeReplica Method (DAO)

MakeReplica Method

Makes a new replica from another database replica (Microsoft Jet workspaces only).

Syntax

VOIDMakeReplica(LPCTSTR pstrPath,

LPCTSTR pstrDescription,

LONG lOptions = -1);

Parameters

Type | Argument | Description
LPCTSTR | pstrPath | A pointer to a string that contains the path and file name of the new replica. If the replica is an existing file name, then an error occurs.
LPCTSTR | pstrDescription | A pointer to a string that describes the replica you are creating.
LONG | lOptions | Optional. A constant or combination of constants that specifies characteristics of the replica you are creating, as specified in Settings.

Settings

You can use one or more of the following constants for lOptions.

Constant | Description
dbRepMakePartial | Creates a partial replica.
dbRepMakeReadOnly | Prevents users from modifying the replicable objects of the new replica; however, when you synchronize the new replica with another member of the replica set, design and data changes will be propagated to the new replica.

Remarks

A newly created partial replica will have all ReplicaFilter properties set to False, meaning that no data will be in the tables.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngin   dben;
CdbDatabase   db;
...                        // Initialize db, etc.
db = dben.OpenDatabase(_T("OriginalReplica.mdb"));
db.MakeReplica(_T("NewReplica.mdb"),
               _T("Copy of OriginalReplica.mdb"),
               dbRepMakeReadOnly);


Move Method (DAO)

Move Method

Moves the position of the current record in a CdbRecordset object.

Syntax

VOIDMove( LONG lRows, CdbBookmark * bm = NULL );

Parameters

Type | Argument | Description
LONG | lRows | A signed value specifying the number of rows the position will move. If rows is greater than 0, the position is moved forward (toward the end of the file). If rows is less than 0, the position is moved backward (toward the beginning of the file).
CdbBookmark * | bm | Pointer to a bookmark. If specified, Move begins relative to this bookmark. If not specified (that is, the default value of NULL is used), Move begins from the current record.

Remarks

If you use Move to position the current record pointer before the first record, the current record pointer moves to the beginning of the file. If the CdbRecordset contains no records and its BOF property is True, using this method to move backward causes an error.

If you use Move to position the current record pointer after the last record, the current record pointer position moves to the end of the file. If the CdbRecordset contains no records and its EOF property is True, then using this method to move forward causes an error.

If either the BOF or EOF property is True and you attempt to use the Move method without a valid bookmark, a run-time error occurs.

Notes

  • When you use Move on a forward-only-type CdbRecordset object, the lRows argument must be a positive integer and bookmarks aren't allowed. This means you can only move forward.

  • To make the first, last, next, or previous record in a Recordset the current record, use either the MoveFirst, MoveLast, MoveNext, or MovePrevious method.

  • Using Move with lRows equal to 0 is an easy way to retrieve the underlying data for the current record. This is useful if you want to make sure that the current record has the most recent data from the base tables. It will also cancel any pending Edit or AddNew calls.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbBookmark bm;
...
recordset.Move( 10 );         // Move forward 10 records.
recordset.Move( -5, &bm );   // Move back 5 records relative to
                           // a given bookmark.


MoveFirst, MoveLast, MoveNext, MovePrevious Methods (DAO)

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Move to the first, last, next, or previous record in a specified Recordset object and make that record the current record.

Syntax

VOIDMoveFirst(VOID);

VOIDMoveLast(LONG lOptions = -1);

VOIDMoveNext(VOID);

VOIDMovePrevious(VOID);

Parameters

Type | Argument | Description
LONG | lOptions = -1 | Optional. If set to the dbRunAsync constant, the method call is asynchronous. You can use the Cancel method to terminate execution of the asynchronous MoveLast method call. You can use the StillExecuting property to determine when the Recordset is fully populated.

Remarks

Use the Move methods to move from record to record without applying a condition.

Caution If you edit the current record, be sure you use the Update method to save the changes before you move to another record. If you move to another record without updating, your changes are lost without warning.

When you open a CdbRecordset, the first record is current and the BO F property is False. If the Recordset contains no records, the BOF property is True, and there is no current record.

If the first or last record is already current when you use MoveFirst or MoveLast, the current record doesn't change.

If you use MovePrevious when the first record is current, the BOF property is True and there is no current record. If you use MovePrevious again, an error occurs and BOF remains True.

If you use MoveNext when the last record is current, the EOF property is True and there is no current record. If you use MoveNext again, an error occurs and EOF remains True.

If recordset refers to a table-type CdbRecordset (Microsoft Jet workspaces only), movement follows the current index. You can set the current index by using the Index property. If you don't set the current index, the order of returned records is undefined.

Important You can use the MoveLast method to fully populate a dynaset- or snapshot-type Recordset to provide the current number of records in the CdbRecordset. However, if you use MoveLast in this way, you can slow down your application's performance. You should only use MoveLast to get a record count if it is absolutely necessary to obtain an accurate record count on a newly opened CdbRecordset. If you use the dbRunAsync constant with MoveLast, the method call is asynchronous. You can use the StillExecuting property to determine when the CdbRecordset is fully populated, and you can use the Cancel method to terminate execution of the asynchronous MoveLast method call.

You can't use the MoveFirst, MoveLast, and MovePrevious methods on a forward-only–type CdbRecordset object.

To move the position of the current record in a CdbRecordset object a specific number of records forward or backward, use the Move method.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDatabase      dbs;
CdbRecordset      rst;
...                        // Initiliaze dbs, etc.
rst = dbs.OpenDatabase(strSQL);
while (!rst.GetEOF())
{
   ...                  // Do some processing.
   rst.MoveNext();      // Get the next record.
}


NewPassword Method (DAO)

NewPassword Method

Changes the password of an existing user account or Microsoft Jet database (Microsoft Jet workspaces only).

Syntax

VOIDNewPassword(LPCTSTR pstrOld,

LPCTSTR pstrNew );

Parameters

Type | Argument | Description
LPCTSTR | pstrOld | A pointer to a string that is the current setting of the Password property of the CdbUser or Microsoft Jet 3.x CdbDatabase object.
LPCTSTR | pstrNew | A pointer to a string that is the new setting of the Password property of the CdbUser or Microsoft Jet 3.x CdbDatabase object.

Remarks

The pstrOld and pstrNew strings can be up to 14 characters long and can include any characters except the ASCII character 0 ( null ). To clear the password, use a zero-length string ("") for newpassword.

Passwords are case-sensitive.

When used from a CdbUser object that is not yet appended to a Users collection, an error occurs. To set a new password, you must either log on as the user whose account you're changing, or you must be a member of the Admins group. The Password property of a CdbUser object is write-only — users can't read the current value.

When used from a Microsoft Jet version 3.0 or later CdbDatabase object, this method offers some security by means of password protection. When you create or open a Microsoft Jet 3.x .mdb file, part of the Connect connection string can describe the password.

If a database has no password, Microsoft Jet will automatically create one by passing a zero-length string ("") for the old password.

Caution If you lose your password, you can never open the database again.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbUser   us;
...
us.NewPassword   (_T("openSesame"),  _T("enterFreely"));


NextRecordset Method (DAO)

NextRecordset Method

Gets the next set of records, if any, returned by a multi-part select query in an OpenRecordset call, and returns a value indicating whether one or more additional records are pending (ODBCDirect workspaces only).

Syntax

BOOLNextRecordset(VOID);

Returns

TRUE indicates the next set of records is available; FALSE indicates that no more records are pending and CdbRecordset is now empty.

Remarks

In an ODBCDirect workspace, you can open a CdbRecordset containing more than one select query in the source argument of OpenRecordset, or the SQL property of a select query CdbQueryDef object, as in the following example.

SELECT LastName, FirstName FROM Authors
WHERE LastName = 'Smith';
SELECT Title, ISBN FROM Titles
WHERE Pub_ID = 9999

The returned CdbRecordset will open with the results of the first query. To obtain the result sets of records from subsequent queries, use the NextRecordset method.

If more records are available (that is, there was another select query in the OpenRecordset call or in the SQL property), the records returned from the next query will be loaded into the CdbRecordset, and NextRecordset will return True, indicating that the records are available. When no more records are available (that is, results of the last select query have been loaded into the CdbRecordset), then NextRecordset will return False, and the CdbRecordset will be empty.

You can also use the Cancel method to flush the contents of a CdbRecordset. However, Cancel also flushes any additional records not yet loaded.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
CdbWorkspace      ws;
CdbDatabase      dbs;
CdbRecordset      rst;
LPTSTR            szSelect =       // Two queries...
                  "SELECT LastName, FirstName "
                  "FROM Authors WHERE LastName = 'Smith';"                  "SELECT Title, ISBN FROM Titles WHERE "
                  "Pub_ID = 9999";
...
ws = dben.CreateWorkspace(...,dbUseODBC);
dbs = ws.OpenDatabase(...);
rst    = dbs.OpenRecordset(szSelect);
while( rst.NextRecordset())
{   ...            // Process each query...
   if (Error)
      rst.Cancel();
   else
      rst.Update();
   ...
}
 rst.Close();


OpenConnection Method (DAO)

OpenConnection Method

Opens a CdbConnection object on an ODBC data source (ODBCDirect workspaces only).

Syntax

CdbConnectionOpenConnection(LPCTSTR pstrName,

LONG lOptions = -1L,

BOOL bReadOnly = FALSE,

LPCTSTR pstrConnect = NULL);

Parameters

Type | Argument | Description
LPCTSTR | pstrName | A pointer to a string that contains the name of a registered ODBC data source (DSN). If it doesn't refer to a valid ODBC data source name, an error occurs.
LONG | lOptions | Optional. A Long value that specifies how the ODBC driver manager should prompt the user for connection information such as DSN, user name, and password. Possible values are described in Remarks.
BOOL | bReadOnly | Optional. TRUEOpens a CdbConnection object for read-only access. FALSE(Default) Opens a CdbConnection object for read/write access.
LPCTSTR | pstrConnect | Optional. A pointer to a string that contains the ODBC connect string. See the Connect property for the specific elements and syntax of this string. A prepended "ODBC;" is required. If pstrConnect is omitted (default), the UID and/or PWD will be taken from the UserName and Password properties of the CdbWorkspace.

Settings

The lOptions argument determines if and when to prompt the user to establish the connection, and whether or not to open the connection asynchronously. You can use one of the following constants.

Constant | Description
dbDriverNoPrompt | The ODBC Driver Manager uses the connection string provided in pstrName and pstrConnect. If you don't provide sufficient information, a run-time error occurs.
dbDriverPrompt | The ODBC Driver Manager displays the ODBC Data Sources dialog box, which displays any relevant information supplied in pstrNname or pstrConnect. The connection string is made up of the DSN that the user selects via the dialog boxes, or, if the user doesn't specify a DSN, the default DSN is used.
dbDriverComplete | Default. If the pstrConnect argument includes all the necessary information to complete a connection, the ODBC Driver Manager uses the string in pstrConnect. Otherwise it behaves as it does when you specify dbDriverPrompt.
dbDriverCompleteRequired | This option behaves like dbDriverComplete except the ODBC driver disables the prompts for any information not required to complete the connection.
dbRunAsync | Execute the method asynchronously. This constant may be used with any of the other lOptions constants.

Remarks

Use the OpenConnection method to establish a connection to an ODBC data source from an ODBCDirect workspace. The OpenConnection method is similar but not equivalent to OpenDatabase. The main difference is that OpenConnection is available only in an ODBCDirect workspace.

If you specify a registered ODBC data source name (DSN) in the connect argument, then the pstrName argument can be any valid string, and will also provide the Name property for the CdbConnection object. If a valid DSN is not included in the pstrConnect argument, then pstrName must refer to a valid ODBC DSN, which will also be the Name property. If neither name nor pstrConnect contains a valid DSN, the ODBC driver manager can be set (via the lOptions argument) to prompt the user for the required connection information. The DSN supplied through the prompt then provides the Name property.

OpenConnection returns a CdbConnection object which contains information about the connection. The CdbConnection object is similar to a CdbDatabase object. The principal difference is that a CdbDatabase object usually represents a database, although it can be used to represent a connection to an ODBC data source from a Microsoft Jet workspace.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbDBEngine      dben(..., dbUseODBC);
CdbConnection   conn;
CdbRecordset      rstX;
conn = dben.OpenConnection(_T("ODBC;..."), dbDriverNoPrompt,
                           FALSE, T("DATABASE=SomeDB..."));
rstX = conn.OpenRecordset(...);


OpenDatabase Method (DAO)

OpenDatabase Method

Opens a specified database in a CdbWorkspace object and returns a reference to the CdbDatabase object that represents it.

Syntax

CdbDatabaseOpenDatabase(LPCTSTR pstrName,

LONG IOptions = -1L,

BOOL bReadOnly = FALSE,

LPCTSTR pstrConnect = NULL);

Parameters

Type | Argument | Description
LPCTSTR | pstrName | A pointer to a string that is the name of an existing Microsoft Jet database file or the data source name (DSN) of an ODBC data source. See the Name property for more information about setting this value.
LONG | lOptions | Optional. A Long value that specifies how the ODBC driver manager should prompt the user for connection information such as DSN, user name, and password. Possible values are described in Remarks.
BOOL | bReadOnly | Optional. TRUEOpens the database with read-only access. FALSE(Default) Opens the database with read/write access.
LPCTSTR | pstrConnect | Optional. A pointer to a string composed of a database type specifier and zero or more parameters separated by semicolons. This parameter passes additional information to ODBC and certain ISAM drivers as needed.

Settings

For ODBCDirect workspaces, the IOptions argument determines if and when to prompt the user to establish the connection. You can use one of the following constants.

Constant | Description
dbDriverNoPrompt | The ODBC Driver Manager uses the connection string provided in pstrName and pstrConnect. If you don't provide sufficient information, a run-time error occurs.
dbDriverPrompt | The ODBC Driver Manager displays the ODBC Data Sources dialog box, which displays any relevant information supplied in pstrName or pstrConnect. The connection string is made up of the DSN that the user selects via the dialog boxes, or, if the user doesn't specify a DSN, the default DSN is used.
dbDriverComplete | (Default) If the pstrConnect and pstrName arguments include all the necessary information to complete a connection, the ODBC Driver Manager uses the string in connect. Otherwise it behaves as it does when you specify dbDriverPrompt.
dbDriverCompleteRequired | This option behaves like dbDriverComplete except the ODBC driver disables the prompts for any information not required to complete the connection.

Remarks

When you open a database, it is automatically added to the Databases collection. Further, in an ODBCDirect workspace, the CdbConnection object corresponding to the new CdbDatabase object is also created and appended to the Connections collection of the same CdbWorkspace object.

Some considerations apply when you use pstrName:

  • If it refers to a database that is already open for exclusive access by another user, an error occurs.

  • If it doesn't refer to an existing database or valid ODBC data source name, an error occurs.

  • If it's a zero-length string ("") and pstrConnect is "ODBC;", a dialog box listing all registered ODBC data source names is displayed so the user can select a database.

  • If you're opening a database through an ODBCDirect workspace and you provide the DSN in pstrConnect, you can set pstrName to a string of your choice that you can use to reference this database in subsequent code.

The pstrConnect argument is expressed in two parts: the database type, followed by a semicolon (;) and the optional arguments. You must first provide the database type, such as "ODBC;" or "FoxPro 2.5;". The optional arguments follow in no particular order, separated by semicolons. One of the parameters may be the password (if one is assigned). For example:

"FoxPro 2.5; pwd=mypassword"

Using the NewPassword method on a CdbDatabase object other than an ODBCDirect database changes the password parameter that appears in the ";pwd=..." part of this argument. You must supply the lOptions and bReadOnly arguments to supply a source string. See the Connect property for syntax.

To close a database, and thus remove the CdbDatabase object from the Databases collection, use the Close method on the object.

Note When you access a Microsoft Jet-connected ODBC data source, you can improve your application's performance by opening a CdbDatabase object connected to the ODBC data source, rather than by linking individual CdbTableDef objects to specific tables in the ODBC data source.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbDBEngine      dben;
CdbDatabase      db;
// Open a local Jet database in exclusive, read/write mode.
db = dben.OpenDatabase(_T("C:\\YourJetDB.mdb"), TRUE);


OpenRecordset Method (DAO)

OpenRecordset Method

Creates a new CdbRecordset object and appends it to the Recordsets collection.

Syntax: CdbConnection, CdbDatabase

CdbRecordsetOpenRecordset(LPCTSTR pstrSource,

LONG lType = -1,

LONG lOptions = -1,

LONG lLockEdits = -1);

Syntax: CdbQueryDef

CdbRecordsetOpenRecordset(LONG lType = -1,

LONG lOptions = -1,

LONG lLockEdits = -1);

Syntax: CdbRecordset, CdbTableDef

CdbRecordsetOpenRecordset(LONG lType = -1,

LONG lOptions = -1);

Parameters

Type | Argument | Description
LPCTSTR | pstrSource | A pointer to a string specifying the source of the records for the new CdbRecordset. The source can be a table name, a query name, or an SQL statement that returns records. For table-type CdbRecordset objects in Microsoft Jet databases, the source can only be a table name.
LONG | lType | Optional. A constant that indicates the type of CdbRecordset to open, as specified under Settings.
LONG | lOptions | Optional. A combination of constants that specify characteristics of the new CdbRecordset, as listed under Settings.
LONG | lLockEdits | Optional. A constant that determines the locking for the CdbRecordset, as specified under Settings.

Settings

You can use one of the following constants for the IType argument.

Constant | Description
dbOpenTable | Opens a table-type Recordset object (Microsoft Jet workspaces only).
dbOpenDynamic | Opens a dynamic-type Recordset object, which is similar to an ODBC dynamic cursor. (ODBCDirect workspaces only)
dbOpenDynaset | Opens a dynaset-type Recordset object, which is similar to an ODBC keyset cursor.
dbOpenSnapshot | Opens a snapshot-type Recordset object, which is similar to an ODBC static cursor.
dbOpenForwardOnly | Opens a forward-only-type Recordset object.

Note If you open a CdbRecordset in a Microsoft Jet workspace and you don't specify a type, OpenRecordset creates a table-type CdbRecordset, if possible. If you specify a linked table or query, OpenRecordset creates a dynaset-type CdbRecordset. In an ODBCDirect workspace, the default setting is dbOpenForwardOnly.

You can use a combination of the following constants for the IOptions argument.

Constant | Description
dbAppendOnly | Allows users to append new records to the Recordset, but prevents them from editing or deleting existing records (Microsoft Jet dynaset-type CdbRecordset only).
dbSQLPassThrough | Passes an SQL statement to a Microsoft Jet-connected ODBC data source for processing (Microsoft Jet snapshot-type CdbRecordset only).
dbSeeChanges | Generates a run-time error if one user is changing data that another user is editing (Microsoft Jet dynaset-type CdbRecordset only). This is useful in applications where multiple users have simultaneous read/write access to the same data.
dbDenyWrite | Prevents other users from modifying or adding records (Microsoft Jet CdbRecordset objects only).
dbDenyRead | Prevents other users from reading data in a table (Microsoft Jet table-type CdbRecordset only).
dbForwardOnly | Creates a forward-only CdbRecordset (Microsoft Jet snapshot-type CdbRecordset only). It is provided only for backward compatibility, and you should use the dbOpenForwardOnly constant in the lType argument instead of using this option.
dbReadOnly | Prevents users from making changes to the CdbRecordset (Microsoft Jet only). The dbReadOnly constant in the lLockEdits argument replaces this option, which is provided only for backward compatibility.
dbRunAsync | Runs an asynchronous query (ODBCDirect workspaces only).
dbExecDirect | Runs a query by skipping SQLPrepare and directly calling SQLExecDirect (ODBCDirect workspaces only). Use this option only when you’re not opening a CdbRecordset based on a parameter query. For more information, see the "Microsoft ODBC 3.0 Programmer’s Reference."
dbInconsistent | Allows inconsistent updates (Microsoft Jet dynaset-type and snapshot-type CdbRecordset objects only).
dbConsistent | Allows only consistent updates (Microsoft Jet dynaset-type and snapshot-type CdbRecordset objects only).

Note The constants dbConsistent and dbInconsistent are mutually exclusive, and using both causes an error. Supplying an lLockEdits argument when lOptions uses the dbReadOnly constant also causes an error.

You can use the following constants for the ILockEdits argument.

Constant | Description
dbReadOnly | Prevents users from making changes to the Recordset (default for ODBCDirect workspaces). You can use dbReadOnly in either the lOptions argument or the lLockEdits argument, but not both. If you use it for both arguments, a run-time error occurs.
dbPessimistic | Uses pessimistic locking to determine how changes are made to the Recordset in a multiuser environment. The page containing the record you're editing is locked as soon as you use the Edit method (default for Microsoft Jet workspaces).
dbOptimistic | Uses optimistic locking to determine how changes are made to the Recordset in a multiuser environment. The page containing the record is not locked until the Update method is executed.
dbOptimisticValue | Uses optimistic concurrency based on row values (ODBCDirect workspaces only).
dbOptimisticBatch | Enables batch optimistic updating (ODBCDirect workspaces only).

Remarks

From a CdbQueryDef or a dynaset- or snapshot-type CdbRecordset object in a Microsoft Jet workspace, or if pstrSource refers to an SQL statement or a CdbTableDef that represents a linked table, you can't use dbOpenTable for the lType argument; if you do, a run-time error occurs. If you want to use an SQL pass-through query on a linked table in a Microsoft Jet-connected ODBC data source, you must first set the Connect property of the linked table's database to a valid ODBC connection string. If you only need to make a single pass through a CdbRecordset opened from a Microsoft Jet-connected ODBC data source, you can improve performance by using dbOpenForwardOnly for the lType argument.

From a dynaset- or snapshot-type CdbRecordset, the new CdbRecordset is of the same type. From a table-type CdbRecordset object, the type of the new object is a dynaset-type CdbRecordset. You can't open new CdbRecordset objects from forward-only–type or ODBCDirect CdbRecordset objects.

In an ODBCDirect workspace, you can open a CdbRecordset containing more than one select query in the pstrSource argument, such as:

"SELECT LastName, FirstName FROM Authors
WHERE LastName = 'Smith';
SELECT Title, ISBN FROM Titles
WHERE ISBN Like '1-55615-*'"

The returned CdbRecordset will open with the results of the first query. To obtain the result sets of records from subsequent queries, use the NextRecordset method.

Use the dbSeeChanges constant in a Microsoft Jet workspace if you want to trap changes while two or more users are editing or deleting the same record. For example, if two users start editing the same record, the first user to execute the Update method succeeds. When the second user invokes the Update method, a run-time error occurs. Similarly, if the second user tries to use the Delete method to delete the record, and the first user has already changed it, a run-time error occurs.

Typically, if the user gets this error while updating a record, your code should refresh the contents of the fields and retrieve the newly modified values. If the error occurs while deleting a record, your code could display the new record data to the user and a message indicating that the data has recently changed. At this point, your code can request a confirmation that the user still wants to delete the record.

You should also use the dbSeeChanges constant if you open a CdbRecordset in a Microsoft Jet-connected ODBC workspace against a Microsoft SQL Server 6.0 (or later) table that has an IDENTITY column, otherwise an error may result.

In an ODBCDirect workspace, you can execute asynchronous queries by setting the dbRunAsync constant in the lOptions argument. This allows your application to continue processing other statements while the query runs in the background. But, you cannot access the CdbRecordset data until the query has completed. To determine whether the query has finished executing, check the StillExecuting property of the new CdbRecordset. If the query takes longer to complete than you anticipated, you can terminate execution of the query with the Cancel method.

Opening more than one CdbRecordset on an ODBC data source may fail because the connection is busy with a prior OpenRecordset call. One way around this is to use a server-side cursor and ODBCDirect, if the server supports this. Another solution is to fully populate the CdbRecordset by using the MoveLast method as soon as the CdbRecordset is opened.

If you open a CdbConnection object with DefaultCursorDriver set to dbUseClientBatchCursor, you can open a CdbRecordset to cache changes to the data (known as batch updating) in an ODBCDirect workspace. Include dbOptimisticBatch in the ILockedits argument to enable update caching. See the Update method topic for details about how to write changes to disk immediately, or to cache changes and write them to disk as a batch.

Closing a CdbRecordset with the Close method automatically deletes it from the Recordsets collection.

Note If pstrSource refers to an SQL statement composed of a string concatenated with a non-integer value, and the system parameters specify a non-U.S. decimal character such as a comma (for example, strSQL = "PRICE > " & lngPrice and lngPrice = 125,50), an error occurs when you try to open the CdbRecordset. This is because during concatenation, the number will be converted to a string using your system's default decimal character, and SQL only accepts U.S. decimal characters.

Usage: Database

#include <afxole.h>
#include <dbdao.h>

CdbDatabase      db;
CdbRecordset      rst;
CString         strSql = _T("SELECT * FROM PARTS");
...                              // Initialize db, etc.
rst = db.OpenRecordset((LPCTSTR)strSql, dbOpenDynaset,                               dbDenyWrite, dbPessimistic);

Usage: QueryDef

#include <afxole.h>
#include <dbdao.h>

CdbQueryDef      qd;
CdbRecordset      rst;
...               // Initialize qd, etc.
rst = qd.OpenRecordset( dbOpenDynaset, dbDenyWrite, dbPessimistic);

Usage: TableDef

#include <afxole.h>
#include <dbdao.h>

CdbDBEnghine      dben;
CdbDatabase      dbs;
CdbRecordset      rst;
CdbTableDef      td;
CdbField         fld;
   // Initialize the TableDef.
dbs = dben.OpenDatabase(...);
td = dbs.CreateTableDef(...);
fld = td.CreateField(...);
td.Fields.Append(fld);
dbs.TableDefs.Append(td);
   // Open a recordset based on the TableDef.
rst = td.OpenRecordset( dbOpenTable, dbAppendOnly );


PopulatePartial Method (DAO)

PopulatePartial Method

Synchronizes any changes in a partial replica with the full replica, clears all records in the partial replica, and then repopulates the partial replica based on the current replica filters. (Microsoft Jet databases only.)

Syntax

database.PopulatePartial dbname

The PopulatePartial method syntax has the following parts.

Part | Description
database | An object variable that references the partial replica Database object that you want to populate.
dbname | A string specifying the path and name of the full replica from which to populate records.

Remarks

When you synchronize a partial replica with a full replica, it is possible to create "orphaned" records in the partial replica. For example, suppose you have a Customers table with its ReplicaFilter set to "Region = 'CA'". If a user changes a customer's region from CA to NY in the partial replica, and then a synchronization occurs via the Synchronize method, the change is propagated to the full replica but the record containing NY in the partial replica is orphaned because it now doesn't meet the replica filter criteria.

To solve the problem of orphaned records, you can use the PopulatePartial method. The PopulatePartial method is similar to the Synchronize method, but it synchronizes any changes with the full replica, removes all records in the partial replica, and then repopulates the partial replica based on the current replica filters. Even if your replica filters have not changed, PopulatePartial will always clear all records in the partial replica and repopulate it based on the current filters.

Generally, you should use the PopulatePartial method when you create a partial replica and whenever you change your replica filters. If your application changes replica filters, you should follow these steps:

  1. Synchronize your full replica with the partial replica in which the filters are being changed.

  2. Use the ReplicaFilter and PartialReplica properties to make the desired changes to the replica filter.

  3. Call the PopulatePartial method to remove all records from the partial replica and transfer all records from the full replica that meet the new replica filter criteria.

If a replica filter has changed and the Synchronize method is invoked without first invoking PopulatePartial, a trappable error occurs.

The PopulatePartial method can only be invoked on a partial replica that has been opened for exclusive access. Furthermore, you can't call the PopulatePartial method from code running within the partial replica itself. Instead, open the partial replica exclusively from the full replica or another database, then call PopulatePartial.

Note Although PopulatePartial performs a one-way synchronization before clearing and repopulating the partial replica, it is still a good idea to call Synchronize before calling PopulatePartial. This is because if the call to Synchronize fails, a trappable error occurs. You can use this error to decide whether or not to proceed with the PopulatePartial method (which removes all records in the partial replica). If PopulatePartial is called by itself and an error occurs while records are being synchronized, records in the partial replica will still be cleared, which may not be the desired result.


Refresh Method (DAO)

Refresh Method

Updates the objects in a collection to reflect the current database's schema.

Syntax

VOID collection.Refresh( VOID );

The collection placeholder is an object variable that represents a persistent collection.

Remarks

You can't use the Refresh method with collections that aren't persistent, such as Connections, Databases, Recordsets, Workspaces, or the QueryDefs collection of a Connection object.

To determine the position that the Microsoft Jet database engine uses for CdbField objects in the Fields collection of a CdbQueryDef, CdbRecordset, or CdbTableDef object, use the OrdinalPosition property of each CdbField object. Changing the OrdinalPosition property of a CdbField object may not change the order of the CdbField objects in the collection until you use the Refresh method.

Use the Refresh method in multiuser environments in which other users may change the database. You may also need to use it on any collections that are indirectly affected by changes to the database. For example, if you change a Users collection, you may need to refresh a Groups collection before using the Groups collection.

A collection is filled with objects the first time it's referred to and won't automatically reflect subsequent changes other users make. If it's likely that another user has changed a collection, use the Refresh method on the collection immediately before carrying out any task in your application that assumes the presence or absence of a particular object in the collection. This will ensure that the collection is as up-to-date as possible. On the other hand, using Refresh can unnecessarily slow performance.


RefreshLink Method (DAO)

RefreshLink Method

Updates the connection information for a linked table (Microsoft Jet workspaces only).

Syntax

VOIDRefreshLink(VOID);

Remarks

To change the connection information for a linked table, reset the Connect property of the corresponding CdbTableDef object and then use the RefreshLink method to update the information. Using RefreshLink method doesn't change the linked table's properties and CdbRelation objects.

For this connection information to exist in all collections associated with the CdbTableDef object that represents the linked table, you must use the Refresh method on each collection.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbTableDef      td;
...
td.SetConnect(_T("Excel 8.0;drive:\path\filename.xls"));
td.RefreshLink();


RegisterDatabase Method (DAO)

RegisterDatabase Method

Enters connection information for an ODBC data source in the Windows Registry. The ODBC driver needs connection information when the ODBC data source is opened during a session.

Syntax

VOIDRegisterDatabase(LPCTSTR pstrDatabase,

LPCTSTR pstrDriver,

BOOL bSilent,

LPCTSTR pstrAttributes );

Parameters

Type | Argument | Description
LPCTSTR | pstrDatabase | A pointer to a string that is the name used in the OpenDatabase method. It refers to a block of descriptive information about the data source. For example, if the data source is an ODBC remote database, it could be the name of the server.
LPCTSTR | pstrDriver | A pointer to a string that is the name of the ODBC driver. This isn't the name of the ODBC driver DLL file. For example, SQL Server is a driver name, but SQLSRVR.DLL is the name of a DLL file. You must have ODBC and the appropriate driver already installed.
BOOL | bSilent | TRUEDoesn't display the ODBC driver dialog boxes that prompt for driver-specific information. The next parameter, Attributes, must contain all the necessary driver-specific information or the dialog boxes are displayed anyway. FALSEDisplays the ODBC driver dialog boxes.
LPCTSTR | pstrAttributes | A pointer to a string that is a list of keywords to be added to the Windows registry. The keywords are in a carriage-return-delimited string.

Remarks

If the database is already registered (connection information is already entered) in the Windows Registry when you use the RegisterDatabase method, the connection information is updated.

If the RegisterDatabase method fails for any reason, no changes are made to the Windows Registry, and an error occurs.

For more information about ODBC drivers such as SQL Server, see the documentation provided with the driver.

You should use the ODBC Data Sources dialog box in the Control Panel to add new data sources, or to make changes to existing entries. However, if you use the RegisterDatabase method, you should set the bSilent option to True.

Usage

/*
   Register a Microsoft SQL Server data source named 'Publishers'
   in the Windows registry. (The Windows ODBC Control Panel icon
   is the preferred way to create, modify, or delete data source    names.)
   Notes:
   1) Specify IniPath, DefaultUser, DefaultPassword, etc. as
      desired in place of the ellipses.
*/
#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben(FALSE,TRUE,...,...,...,dbUseODBC); // note 1
CdbDatabase       dbsRegister;
LPCTSTR
   lpctstrAttribute =
      _T("Database=pubs\rDescription=Publishers\r
      OemToAnsi=No\rServer=Server1"),
   lpctstrNotice =
      _T("Use regedit.exe to view changes:
      HKEY_CURRENT_USER\Software\ODBC\ODBC.INI");

dbsRegister = dben.OpenDatabase(_T("Publishers"));
try
{
dben.RegisterDatabase(_T("Publishers"),
                      _T("SQL Server"),
                      TRUE, lpctstrAttribute );
printf(lpctstrNotice);
}
catch (CdbException)
{
for (long ct = 0; ct < dben.Errors.GetCount(); ct++)
   {
   printf(_T("Error #%ld: #%ld -- %s\n"),
      ct,
      dben.Errors[ct].GetNumber(),
      dben.Errors[ct].GetDescription());
   }
}


RepairDatabase Method (DAO)

RepairDatabase Method

Attempts to repair a corrupted Microsoft Jet database (Microsoft Jet databases only).

Syntax

VOIDRepairDatabase(LPCTSTR pstrDatabase );

Parameters

Type | Argument | Description
LPCTSTR | pstrDatabase | A pointer to a string that contains the path and file name of an existing Microsoft Jet database file. If you omit the path, only the current directory is searched. If your system supports the uniform naming convention (UNC), you can also specify a network path, such as "\\server1\share1\dir1\db1.mdb".

Remarks

You must close the database specified by pstrDatabase before you repair it. In a multiuser environment, other users can't have pstrDatabase open while you're repairing it. If pstrDatabase isn't closed or isn't available for exclusive use, an error occurs.

This method attempts to repair a database that was marked as possibly corrupt by an incomplete write operation. This can occur if an application using the Microsoft Jet database engine is closed unexpectedly because of a power outage or computer hardware problem. The database won't be marked as possibly corrupt if you use the Close method or if you quit your application in a usual way.

The RepairDatabase method also attempts to validate all system tables and all indexes. Any data that can't be repaired is discarded. If the database can't be repaired, a run-time error occurs.

When you attempt to open or compact a corrupted database, a run-time error usually occurs. In some situations, however, a corrupted database may not be detected, and no error occurs. It's a good idea to provide your users with a way to use the RepairDatabase method in your application if their database behaves unpredictably.

Some types of databases can become corrupted if a user ends an application without closing CdbDatabase or CdbRecordset objects and the Microsoft Jet database engine; Microsoft Windows doesn't have a chance to write data caches to disk. To avoid corrupt databases, establish procedures for closing applications and shutting down systems that ensure that all cached pages are saved to the database. In some cases, power supplies that can't be interrupted may be necessary to prevent accidental data loss during power fluctuations.

Note After repairing a database, it's also a good idea to compact it using the CompactDatabase method to defragment the file and to recover disk space.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbDBEngine   dben;
...                     // Attempt to repair a local database
dben.RepairDatabase(_T("db1.mdb"));


Requery Method (DAO)

Requery Method

Updates the data in a CdbRecordset object by re-executing the query on which the object is based.

Syntax

VOIDRequery(CdbQueryDef *pq = NULL);

Parameters

Type | Argument | Description
CdbQueryDef * | pq | Optional. Pointer to a CdbQueryDef object (Microsoft Jet workspaces only).

Remarks

Use this method to make sure that a CdbRecordset contains the most recent data. This method re-populates the current CdbRecordset by using either the current query parameters or (in a Microsoft Jet workspace) the new ones supplied by the pg argument.

In an ODBCDirect workspace, if the original query was asynchronous, then Requery will also execute an asynchronous query.

If you don't specify a pg argument, the CdbRecordset is re-populated based on the same query definition and parameters used to originally populate the CdbRecordset. Any changes to the underlying data will be reflected during this re-population. If you didn't use a QueryDef to create the CdbRecordset, the CdbRecordset is re-created from scratch.

If you specify the original CdbQueryDef in the pg argument, then the CdbRecordset is requeried using the parameters specified by the CdbQueryDef. Any changes to the underlying data will be reflected during this re-population. To reflect any changes to the query parameter values in the CdbRecordset, you must supply the pgf argument.

If you specify a different CdbQueryDef than what was originally used to create the CdbRecordset, the CdbRecordset is re-created from scratch.

When you use Requery, the first record in the CdbRecordset becomes the current record.

You can't use the Requery method on dynaset- or snapshot-type CdbRecordset objects whose Restartable property is set to False. However, if you supply the optional pg argument, the Restartable property is ignored.

If both the BOF and EOF property settings of the CdbRecordset object are True after you use the Requery method, the query didn't return any records and the CdbRecordset contains no data.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset recordset;
...
recordset.Edit();         // Make some changes
...
recordset.Update;         // Save changes
recordset.Requery();     // Refresh the recordset


Seek Method (DAO)

Seek Method

Locates the record in an indexed table-type CdbRecordset object that satisfies the specified criteria for the current index and makes that record the current record (Microsoft Jet workspaces only).

Syntax

VOIDSeek(LPCTSTR pstrComparison,

LONG lNumFields,

COleVariant cKey,

...);

Parameters

Type | Argument | Description
LPCTSTR | pstrComparison | One of the following string expressions: <, <=, =, >=, or >.
LONG | lNumFields | The number of key arguments that follow. This argument may have a value from 1 to 13. (The maximum value of this parameter is defined by DAO_MAXSEEKFIELDS.)
COleVariant | cKey, ... | One or more values corresponding to fields in the CdbRecordset object's current index, as specified by its Index property setting. Seek accepts an unspecified number of arguments, as indicated by the ellipsis symbol ("..."), however you may only have a maximum of 13 key arguments.

Remarks

You must set the current index with the Index property before you use Seek. If the index identifies a nonunique key field, Seek locates the first record that satisfies the criteria.

The Seek method searches through the specified key fields and locates the first record that satisfies the criteria specified by pstrComparison and cKey. Once found, it makes that record current and sets the NoMatch property to False. If the Seek method fails to locate a match, the NoMatch property is set to True, and the current record is undefined.

If pstrComparison is equal (=), greater than or equal (>=), or greater than (>), Seek starts at the beginning of the index and searches forward.

If pstrComparison is less than (<) or less than or equal (<=), Seek starts at the end of the index and searches backward. However, if there are duplicate index entries at the end of the index, Seek starts at an arbitrary entry among the duplicates and then searches backward.

You must specify values for all fields defined in the index. If you use Seek with a multiple-column index, and you don't specify a comparison value for every field in the index, then you cannot use the equal (=) operator in the comparison. That's because some of the cKey criteria fields will default to Null, which will probably not match. Therefore, the equal operator will work correctly only if you have a record which is all Null except the key you're looking for. It's recommended that you use the greater than or equal (>=) operator instead.

The cKey argument must be of the same field data type as the corresponding field in the current index. For example, if the current index refers to a number field (such as Employee ID), cKey must be numeric.

There doesn't have to be a current record when you use Seek.

You can use the Indexes collection to enumerate the existing indexes.

To locate a record in a dynaset- or snapshot-type CdbRecordset that satisfies a specific condition that is not covered by existing indexes, use the Find methods. To include all records, not just those that satisfy a specific condition, use the Move methods to move from record to record.

You can't use the Seek method on a linked table because you can't open linked tables as table-type Recordset objects. However, if you use the OpenDatabase method to directly open an installable ISAM (non-ODBC) database, you can use Seek on tables in that database.

In an ODBCDirect workspace, the Find and Seek methods are not available on any type of CdbRecordset object, because executing a Find or Seek through an ODBC connection is not very efficient over the network. Instead, you should design the query (that is, using the pstrSource argument to the OpenRecordset method) with an appropriate WHERE clause that restricts the returned records to only those that meet the criteria you would otherwise use in a Find or Seek.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
CdbDatabase      dbs;
CdbRecordset      rst;
...
   // Open a table-type recordset.
rst = dbs.OpenRecordset(..., dbOpenTable);
   // Define current index as the LastName index.
rst.SetIndex(_T("LastName"));
   // Seek first record with last name equal to Smith
rst.Seek("=", 1, _T("Smith"));


SetOption Method (DAO)

SetOption Method

Temporarily overrides values for the Microsoft Jet database engine keys in the Windows Registry (Microsoft Jet workspaces only).

Syntax

VOIDSetOption(LONG lOptions,

LPVARIANT pvValue );

Parameters

Type | Argument | Description
LONG | lOptions | A Long which specifies the registry key. Possible values are described in Remarks.
LPVARIANT | pvValue | A pointer to a variant which specifies a new value for the registry key.

Settings

Each constant refers to the corresponding registry key in the path Jet\3.5\Engines\Jet 3.5\ (that is, dbSharedAsyncDelay corresponds to the key Jet\3.5\Engines\Jet 3.5\SharedAsyncDelay, and so on.).

Constant | Description
dbPageTimeout | The PageTimeout key
dbSharedAsyncDelay | The SharedAsyncDelay key
dbExclusiveAsyncDelay | The ExclusiveAsyncDelay key
dbLockRetry | The LockRetry key
dbUserCommitSync | The UserCommitSync key
dbImplicitCommitSync | The ImplicitCommitSync key
dbMaxBufferSize | The MaxBufferSize key
dbMaxLocksPerFile | The MaxLocksPerFile key
dbLockDelay | The LockDelay key
dbRecycleLVs | The RecycleLVs key
dbFlushTransactionTimeout | The FlushTransactionTimeout key

Remarks

Use the SetOption method to override registry values at run-time. New values established with the SetOption method remain in effect until changed again by another SetOption call, or until the DBEngine object is closed.

For further details on what the registry keys do, and appropriate values to set them to, see Initializing the Microsoft Jet 3.5 Database Engine.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
COleVariant      vExclusiveAsyncDelay(10, VT_I2),
               vSharedAsyncDelay(15, VT_I2);
...
dben.SetOption(dbExclusiveAsyncDelay, &vExclusiveAsyncDelay);
dben.SetOption(dbSharedAsyncDelay,  &vSharedAsyncDelay);
...


Start Method (dbDAO)

Start Method

Explicitly starts the Microsoft Jet database engine rather than letting the constructor for a CdbDBEngine object implicitly start the engine.

Syntax

VOIDStart(VOID);

Remarks

Before invoking this method, set the desired CdbDBEngine object properties to customize the operation of the Microsoft Jet database engine.

Usage

#include <afxole.h>
#include <dbdao.h>
...
// Your main program
CdbDBEngine   dben(FALSE,FALSE);   // Don't start yet.
YourInitialization( &dben );      // Call your DLL.
...
// Your DLL
void YourInitialization(CdbDBEngine *pdbEngine)
{
pdbEngine->SetDefaultUser(_T("YourUserName"));
pdbEngine->SetDefaultPassword(_T("YourPassword"));
pdbEngine->SetSystemDB(_T("c:\\YourDatabase.mdb"));
pdbEngine->Start();               // Now start Jet
}


Synchronize Method (DAO)

Synchronize Method

Synchronizes two replicas. (Microsoft Jet databases only).

Syntax

VOIDSynchronize(LPCTSTR pstrReplica,

LONG lType = -1);

Parameters

Type | Argument | Description
LPCTSTR | pstrReplica | A pointer to a string that contains the path to the target replica with which this database will be synchronized. The .mdb file name extension is optional.
LONG | lType | Optional. A constant indicating which direction to synchronize changes between the two databases, as specified in Settings.

Settings

You can use the following constants in the second argument. You can use one of the first three constants with or without the fourth constant.

Constant | Description
dbRepExportChanges | Sends changes from database object to pstrReplica.
dbRepImportChanges | Sends changes from pstrReplica to database object.
dbRepImpExpChanges | (Default) Sends changes from database object to pstrReplica, and vice-versa, also known as bi-directional exchange.
dbRepSyncInternet | Exchanges data between files connected by an Internet pathway.

Remarks

You use Synchronize to exchange data and design changes between two databases. Design changes always happen first. Both databases must be at the same design level before they can exchange data. For example, an exchange of type dbRepExportChanges might cause design changes at a replica even though data changes flow only from the database to pstrReplica.

The replica identified in pstrReplica must be part of the same replica set. If both replicas have the same ReplicaID property setting or are Design Masters for two different replica sets, the synchronization fails.

When you synchronize two replicas over the Internet, you must use the dbRepSyncInternet constant. In this case, you specify a Uniform Resource Locator (URL) address for the pstrReplica argument instead of specifying a local area network path.

Note You can't synchronize partial replicas with other partial replicas. See the PopulatePartial method for more information.

Synchronization over the Internet requires the Replication Manager, which is only available in the Microsoft Office 97, Developer Edition.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngin   dben;
CdbDatabase   db;
...                        // Initialize db, etc.
db = dben.OpenDatabase(_T("OutOfDateReplica.mdb"));
db.Synchronize(_T("file:\\website\UpToDateReplica.mdb"),
                  (dbRepImpExpChanges|dbRepSyncInternet));


Update Method (DAO)

Update Method

Saves the contents of the copy buffer to an updatable CdbRecordset object.

Syntax

VOIDUpdate(short sType = dbUpdateRegular,

VARIANT_BOOL bForce = FALSE);

Parameters

Type | Argument | Description
SHORT | sType | Optional. A constant indicating the type of update, as specified in Settings (ODBCDirect workspaces only).
VARIANT_BOOL | bForce | Optional. A Boolean value indicating whether or not to force the changes into the database, regardless of whether the underlying data has been changed by another user since the AddNew, Delete, or Edit call. If True, the changes are forced and changes made by other users are simply overwritten. If False (default), changes made by another user while the update is pending will cause the update to fail for those changes that are in conflict. No error occurs, but the BatchCollisionCount and BatchCollisions properties will indicate the number of conflicts and the rows affected by conflicts, respectively (ODBCDirect workspaces only).

Settings

You can use the following values for the sType argument. You can use the non-default values only if batch updating is enabled.

Constant | Description
dbUpdateRegular | Default. Pending changes aren’t cached and are written to disk immediately.
dbUpdateBatch | All pending changes in the update cache are written to disk.
dbUpdateCurrentRecord | Only the current record’s pending changes are written to disk.

Remarks

Use Update to save the current record and any changes you've made to it.

Caution Changes to the current record are lost if:

  • You use the Edit or AddNew method, and then move to another record without first using Update.

  • You use Edit or AddNew, and then use Edit or AddNew again without first using Update.

  • You set the Bookmark property to another record.

  • You close the Recordset without first using Update.

  • You cancel the Edit operation by using CancelUpdate.

To edit a record, use the Edit method to copy the contents of the current record to the copy buffer. If you don't use Edit first, an error occurs when you use Update or attempt to change a field's value.

In an ODBCDirect workspace, you can do batch updates, provided the cursor library supports batch updates, and the CdbRecordset was opened with the optimistic batch locking option.

In a Microsoft Jet workspace, when the CdbRecordset object's LockEdits property setting is True (pessimistically locked) in a multiuser environment, the record remains locked from the time Edit is used until the Update method is executed or the edit is canceled. If the LockEdits property setting is False (optimistically locked), the record is locked and compared with the pre-edited record just before it is updated in the database. If the record has changed since you used the Edit method, the Update operation fails. Microsoft Jet-connected ODBC and installable ISAM databases always use optimistic locking. To continue the Update operation with your changes, use the Update method again. To revert to the record as the other user changed it, refresh the current record by using Move 0.

Note To add, edit, or delete a record, there must be a unique index on the record in the underlying data source. If not, a “Permission denied” error will occur on the AddNew, Delete, or Edit method call in a Microsoft Jet workspace, or an “Invalid argument” error will occur on the Update call in an ODBCDirect workspace.

Usage

#include <afxole.h>
#include <dbdao.h>

COleVariant       vVal(_T("LastName"), VT_BSTRT);
CdbRecordset      rst;
...               // Intialize recordset etc.
rst.Edit();
rst.SetField( 0L, vVal);      // Edit the first field.
rst.Update(dbUpdateCurrentRecord, TRUE);


DAO Properties by Object

This reference groups all DAO properties by object. To determine whether a particular property is available to Microsoft Jet or ODBC databases, check the Help topic for that property.

CdbConnection

CdbContainer

CdbDatabase

CdbDBEngine

CdbDocument

CdbError

CdbField

CdbGroup

CdbIndex

 CdbParameter

CdbProperty

CdbQueryDef

CdbRecordset

CdbRelation

CdbTableDef

CdbUser

CdbWorkspace


DAO Properties for Microsoft Jet Workspaces

This reference lists alphabetically all DAO properties available to Microsoft Jet workspaces.

A-C

AbsolutePosition

AllowZeroLength

AllPermissions

Attributes

BOF

Bookmark

Bookmarkable

CacheSize

 CacheStart

Clustered

CollatingOrder

CollectionIndex

ConflictTable

Connect

Container

Count

D-H

DataUpdatable

DateCreated

DefaultUser

DefaultPassword

DefaultValue

Description

DesignMasterID

DistinctCount

 EditMode

EOF

Filter

Foreign

ForeignName

ForeignTable

HelpContext

HelpFile

I-O

IgnoreNulls

Index

Inherit

Inherited

IniPath

IsolateODBCTrans

KeepLocal

LastModified

LastUpdated

LockEdits

 LoginTimeout

LogMessages

MaxRecords

Name

NoMatch

Number

ODBCTimeout

OrdinalPosition

Owner

P-R

PartialReplica

Password

PercentPosition

Permissions

PID

Primary

QueryTimeout

RecordCount

 RecordsAffected

Replicable

ReplicableBool

ReplicaFilter

ReplicaID

Required

Restartable

ReturnsRecords

S-Z

Size

Sort

Source

SourceField

SourceTable

SourceTableName

SQL

SystemDB

Table

Transactions

 Type

Unique

Updatable

UserName

V1xNullBehavior

ValidateOnSet

ValidationRule

ValidationText

Value

Version


DAO Properties for ODBCDirect Workspaces

This reference lists alphabetically all DAO properties available to ODBCDirect workspaces.

A-D

AbsolutePosition

Attributes

BatchCollisionCount

BatchCollisions

BatchSize

BOF

Bookmark

Bookmarkable

CacheSize

CollectionIndex

 Connect

Connection

Count

Database

DataUpdatable

DefaultCursorDriver

DefaultType

Description

Direction

E-Q

EditMode

EOF

HelpContext

HelpFile

LastModified

LockEdits

LoginTimeout

LogMessages

 MaxRecordsdvproMaxRecords

Name

Number

ODBCTimeout

OrdinalPosition

OriginalValue

PercentPosition

Prepare

QueryTimeout

R-Z

RecordCount

RecordsAffected

RecordStatus

Restartable

Size

Source

SourceField

SourceTable

SQL

 StillExecuting

Transactions

Type

Updatable

UpdateOptions

UserName

Value

Version

VisibleValue


AbsolutePosition Property (DAO)

AbsolutePosition Property

Sets or returns the relative record number of a CdbRecordset object's current record.

Syntax

VOIDSetAbsolutePosition(LONG lPosition);

LONGGetAbsolutePosition(VOID);

Parameters

Type | Argument | Description
LONG | lPosition | A Long containing a relative record number from 0 to one less than the number of records in the CdbRecordset.

Remarks

You can use the AbsolutePosition property to position the current record pointer to a specific record based on its ordinal position in a dynaset- or snapshot-type CdbRecordset object. You can also determine the current record number by checking the AbsolutePosition property setting.

Because the AbsolutePosition property value is zero-based (that is, a setting of 0 refers to the first record in the CdbRecordset object), you cannot set it to a value greater than or equal to the number of populated records; doing so causes a trappable error. You can determine the number of populated records in the Recordset object by checking the RecordCount property setting. The maximum allowable setting for the AbsolutePosition property is the value of the RecordCount property minus 1.

If there is no current record, as when there are no records in the CdbRecordset object, AbsolutePosition returns –1. If the current record is deleted, the AbsolutePosition property value isn't defined, and a trappable error occurs if it's referenced. New records are added to the end of the sequence.

You shouldn't use this property as a surrogate record number. Bookmarks are still the recommended way of retaining and returning to a given position and are the only way to position the current record across all types of CdbRecordset objects. In particular, the position of a record changes when one or more records preceding it are deleted. There is also no assurance that a record will have the same absolute position if the CdbRecordset object is re-created again because the order of individual records within a CdbRecordset object isn't guaranteed unless it's created with an SQL statement by using an ORDER BY clause.

Notes

  • Setting the AbsolutePosition property to a value greater than zero on a newly opened but unpopulated CdbRecordset object causes a trappable error. Populate the CdbRecordset object first with the MoveLast method.

  • The AbsolutePosition property isn't available on forward-only–type CdbRecordset objects, or on CdbRecordset objects opened from pass-through queries against Microsoft Jet-connected ODBC databases.


AllowZeroLength Property (DAO)

AllowZeroLength Property

Sets or returns a value that indicates whether a zero-length string ("") is a valid setting for the Value property of the CdbField object with a Text or Memo data type.

Syntax

VOIDSetAllowZeroLength(BOOL bFlag);

BOOLGetAllowZeroLength(VOID);

Parameters

Type | Example | Description
BOOL | bFlag | TRUE if the CdbField object accepts a zero-length string as its Value property.

Remarks

For an object not yet appended to the Fields collection, this property is read/write.

Once appended to a Fields collection, the availability of the AllowZeroLength property depends on the object that contains the Fields collection, as shown in the following table.

If the Fields collection belongs to a | Then AllowZeroLength is
CdbIndex object | Not supported
CdbQueryDef object | Read-only
CdbRecordset object | Read-only
CdbRelation object | Not supported
CdbTableDef object | Read/write

You can use this property along with the Required, ValidateOnSet, or ValidationRule property to validate a value in a field.


AllPermissions Property (DAO)

AllPermissions Property

Returns all the permissions that apply to the current UserName property of the CdbContainer or CdbDocument object, including permissions that are specific to the user as well as the permissions a user inherits from memberships in groups (Microsoft Jet workspaces only).

Syntax

LONGGetAllPermissions(VOID);

Remarks

For any CdbContainer or CdbDocument object, the AllPermissions property may include the following.

Constant | The User Can
dbSecReadDef | Read the table definition, including column and index information.
dbSecWriteDef | Modify or delete the table definition, including column and index information.
dbSecRetrieveData | Retrieve data from the CdbDocument object.
dbSecInsertData | Add records.
dbSecReplaceData | Modify records.
dbSecDeleteData | Delete records.

In addition, the Databases container or any CdbDocument object in a Documents collection may include the following.

Constant | The User
dbSecDeleteData | Can delete records.
dbSecDBAdmin | Can replicate the database and change the database password.
dbSecDBCreate | Can create new databases. This setting is valid only on the Databases container in the workgroup information file (System.mdw).
dbSecDBExclusive | Has exclusive access to the database.
dbSecDBOpen | Can open the database.

This property contrasts with the Permissions property, which returns only the permissions that are specific to the user and doesn't include any permissions that the user may also have as a member of groups. If the current value of the UserName property is a group, then the AllPermissions property returns the same values as the Permissions property.


Attributes Property (DAO)

Attributes Property

Sets or returns a value that indicates one or more characteristics of a CdbField, CdbRelation, or CdbTableDef object.

Syntax

VOIDSetAttributes(LONG lValue);

LONGGetAttributes(VOID);

Parameters

Type | Argument | Description
LONG | lValue | A Long with one or more of the values listed in Remarks. The default value is 0.

Remarks

On a CdbField object, the Attributes property specifies characteristics of the object and can be a combination of these constants.

Constant | Description
dbAutoIncrField | The field value for new records is automatically incremented to a unique Long integer that can't be changed (in a Microsoft Jet workspace, supported only for Microsoft Jet database(.mdb) tables).
dbDescending | The field is sorted in descending (Z to A or 100 to 0) order; this option applies only to a CdbField object in a Fields collection of an CdbIndex object. If you omit this constant, the field is sorted in ascending (A to Z or 0 to 100) order. This is the default value for CdbIndex and CdbTableDef fields (Microsoft Jet workspaces only).
dbFixedField | The field size is fixed (default for Numeric fields).
dbHyperlinkField | The field contains hyperlink information (Memo fields only).
dbSystemField | The field stores replication information for replicas; you can't delete this type of field (Microsoft Jet workspaces only).
dbUpdatableField | The field value can be changed.
dbVariableField | The field size is variable (Text fields only).

On a CdbRelation object, the property specifies characteristics of the relationship represented by the CdbRelation object and can be a combination of these constants.

Constant | Description
dbRelationUnique | The relationship is one-to-one.
dbRelationDontEnforce | The relationship isn't enforced (no referential integrity).
dbRelationInherited | The relationship exists in a non-current database that contains the two linked tables.
dbRelationUpdateCascade | Updates will cascade.
dbRelationDeleteCascade | Deletions will cascade.

Note If you set the CdbRelation object's Attributes property to activate cascading operations, the Microsoft Jet database engine automatically updates or deletes records in one or more other tables when changes occur in related primary tables.

For example, suppose you establish a cascading delete relationship between a Customers table and an Orders table. When you delete records from the Customers table, records in the Orders table related to that customer are also deleted. In addition, if you establish cascading delete relationships between the Orders table and other tables, records from those tables are automatically deleted when you delete records from the Customers table.

On a CdbTableDef object, the property specifies characteristics of the table represented by the CdbTableDef object and can be a combination of these constants.

Constant | Description
dbAttachExclusive | For databases that use the Microsoft Jet database engine, the table is a linked table opened for exclusive use. You can set this constant on an appended CdbTableDef object for a local table, but not on a remote table.
dbAttachSavePWD | For databases that use the Microsoft Jet database engine, the user ID and password for the remotely linked table are saved with the connection information. You can set this constant on an appended CdbTableDef object for a remote table, but not on a local table.
dbSystemObject | The table is a system table provided by the Microsoft Jet database engine. You can set this constant on an appended CdbTableDef object.
dbHiddenObject | The table is a hidden table provided by the Microsoft Jet database engine. You can set this constant on an appended CdbTableDef object.
dbAttachedTable | The table is a linked table from a non-ODBC data source such as a Microsoft Jet or Paradox database (read-only).
dbAttachedODBC | The table is a linked table from an ODBC data source, such as Microsoft SQL Server (read-only).

For an object not yet appended to a collection, this property is read/write.

For an appended CdbField object, the availability of the Attributes property depends on the object that contains the Fields collection.

If the CdbField object belongs to an | Then Attributes is
CdbIndex object | Read/write until the CdbTableDef object that the CdbIndex object is appended to is appended to a CdbDatabase object; then the property is read-only.
CdbQueryDef object | Read-only
CdbRecordset object | Read-only
CdbRelation object | Not supported
CdbTableDef object | Read/write

For an appended CdbRelation object, the Attributes property setting is read-only.

For an appended CdbTableDef object, the property is read/write, although you can't set all of the constants if the object is appended, as noted in Settings and Return Values.

When you set multiple attributes, you can combine them by summing the appropriate constants. Any invalid values are ignored without producing an error.


BatchCollisionCount Property (DAO)

BatchCollisionCount Property

Returns the number of records that did not complete the last batch update (ODBCDirect workspaces only).

Syntax

LONGGetBatchCollisionCount(VOID);

Remarks

This property indicates how many records encountered collisions or otherwise failed to update during the last batch update attempt. The value of this property corresponds to the number of bookmarks in the BatchCollisions property.

If you set the working CdbRecordset object's Bookmark property to bookmark values in the BatchCollisions array, you can move to each record that failed to complete the most recent batch Update operation.

After the collision records are corrected, a batch-mode Update method can be called again. At this point DAO attempts another batch update, and the BatchCollisions property again reflects the set of records that failed the second attempt. Any records that succeeded in the previous attempt are not sent in the current attempt, because they now have a RecordStatus property of dbRecordUnmodified. This process can continue as long as collisions occur, or until you abandon the updates and close the result set.


BatchCollisions Property (DAO)

BatchCollisions Property

Returns an array of bookmarks indicating the rows that generated collisions in the last batch update operation (ODBCDirect workspaces only).

Syntax

COleVariantGetBatchCollisions(VOID);

Remarks

This property contains an array of bookmarks to rows that encountered a collision during the last attempted batch Update call. The BatchCollisionCount property indicates the number of elements in the array.

If you set the working CdbRecordset object's Bookmark property to bookmark values in the BatchCollisions array, you can move to each record that failed to complete the most recent batch-mode Update operation.

After the collision records are corrected, you can call the batch mode Update method again. At this point DAO attempts another batch update, and the BatchCollisions property again reflects the set of records that failed the second attempt. Any records that succeeded in the previous attempt are not sent in the current attempt, as they now have a RecordStatus property of dbRecordUnmodified. This process can continue as long as collisions occur, or until you abandon the updates and close the result set.

This array is re-created each time you execute a batch-mode Update method.


BatchSize Property (DAO)

BatchSize Property

Sets or returns the number of statements sent back to the server in each batch (ODBCDirect workspaces only).

Syntax

VOIDSetBatchSize(LONG lSize);

LONGGetBatchSize(VOID);

Parameters

Type | Argument | Description
LONG | lSize | A Long that indicates the number of batched statements sent to the server in a single batch update. The default value is 15.

Remarks

The BatchSize property determines the batch size used when sending statements to the server in a batch update. The value of the property determines the number of statements sent to the server in one command buffer. By default, 15 statements are sent to the server in each batch. This property can be changed at any time. If a database server doesn't support statement batching, you can set this property to 1, causing each statement to be sent separately.


BOF, EOF Properties (DAO)

BOF, EOF Properties

  • BOF returns a value that indicates whether the current record position is before the first record in a CdbRecordset object.

  • EOF returns a value that indicates whether the current record position is after the last record in a CdbRecordset object.

Syntax

BOOLGetBOF(VOID);

BOOLGetEOF(VOID);

Remarks

The BOF property returns True if the current record position is before the first record, and False if the current record position is on or after the first record.

The EOF property returns True if the current record position is after the last record, and False if the current record position is on or before the last record.

You can use the BOF and EOF properties to determine whether a CdbRecordset object contains records or whether you've gone beyond the limits of a CdbRecordset object when you move from record to record.

The location of the current record pointer determines the BOF and EOF return values.

If either the BOF or EOF property is True, there is no current record.

If you open a CdbRecordset object containing no records, the BOF and EOF properties are set to True, and the CdbRecordset object's RecordCount property setting is 0. When you open a Recordset object that contains at least one record, the first record is the current record and the BOF and EOF properties are False; they remain False until you move beyond the beginning or end of the CdbRecordset object by using the MovePrevious or MoveNext method, respectively. When you move beyond the beginning or end of the CdbRecordset, there is no current record or no record exists.

If you delete the last remaining record in the CdbRecordset object, the BOF and EOF properties may remain False until you attempt to reposition the current record.

If you use the MoveLast method on a CdbRecordset object containing records, the last record becomes the current record; if you then use the MoveNext method, the current record becomes invalid and the EOF property is set to True. Conversely, if you use the MoveFirst method on a CdbRecordset object containing records, the first record becomes the current record; if you then use the MovePrevious method, there is no current record and the BOF property is set to True.

Typically, when you work with all the records in a CdbRecordset object, your code will loop through the records by using the MoveNext method until the EOF property is set to True.

If you use the MoveNext method while the EOF property is set to True or the MovePrevious method while the BOF property is set to True, an error occurs.

This table shows which Move methods are allowed with different combinations of the BOF and EOF properties.

 | MoveFirst, MoveLast | MovePrevious, Move < 0 | Move 0 | MoveNext, Move > 0
BOF=True, EOF=False | Allowed | Error | Error | Allowed
BOF=False, EOF=True | Allowed | Allowed | Error | Error
Both True | Error | Error | Error | Error
Both False | Allowed | Allowed | Allowed | Allowed

Allowing a Move method doesn't mean that the method will successfully locate a record. It merely indicates that an attempt to perform the specified Move method is allowed and won't generate an error. The state of the BOF and EOF properties may change as a result of the attempted Move.

An OpenRecordset method internally invokes a MoveFirst method. Therefore, using an OpenRecordset method on an empty set of records sets the BOF and EOF properties to True. (See the following table for the behavior of a failed MoveFirst method.)

All Move methods that successfully locate a record will set both BOF and EOF to False.

In a Microsoft Jet workspace, if you add a record to an empty CdbRecordset, BOF will become False, but EOF will remain True, indicating that the current position is at the end of Recordset. In an ODBCDirect workspace, both BOF and EOF will become False, indicating that the current position is on the new record.

Any Delete method, even if it removes the only remaining record from a CdbRecordset, won't change the setting of the BOF or EOF property.

The following table shows how Move methods that don't locate a record affect the BOF and EOF property settings.

 | BOF | EOF
MoveFirst, MoveLast | True | True
Move 0 | No change | No change
MovePrevious, Move < 0 | True | No change
MoveNext, Move > 0 | No change | True


Bookmark Property (DAO)

Bookmark Property

Sets or returns a bookmark that uniquely identifies the current record in a CdbRecordset object.

Syntax

CdbBookmarkGetBookmark(VOID);

VOIDSetBookmark(class CdbBookmark );

Parameters

Type | Description
Class CdbBookmark | A bookmark of the desired record position.

Remarks

For a CdbRecordset object based entirely on Microsoft Jet tables, the value of the Bookmarkable property is True, and you can use the Bookmark property with that Recordset. Other database products may not support bookmarks, however. For example, you can't use bookmarks in any Recordset object based on a linked Paradox table that has no primary key.

When you create or open a CdbRecordset object, each of its records already has a unique bookmark. You can save the bookmark for the current record by assigning the value of the Bookmark property to a variable. To quickly return to that record at any time after moving to a different record, set the CdbRecordset object's Bookmark property to the value of that variable.

There is no limit to the number of bookmarks you can establish. To create a bookmark for a record other than the current record, move to the desired record and assign the value of the Bookmark property to a String variable that identifies the record.

To make sure the CdbRecordset object supports bookmarks, check the value of its Bookmarkable property before you use the Bookmark property. If the Bookmarkable property is False, the CdbRecordset object doesn't support bookmarks, and using the Bookmark property results in a trappable error.

If you use the Clone method to create a copy of a CdbRecordset object, the Bookmark property settings for the original and the duplicate CdbRecordset objects are identical and can be used interchangeably. However, you can't use bookmarks from different CdbRecordset objects interchangeably, even if they were created by using the same object or the same SQL statement.

If you set the Bookmark property to a value that represents a deleted record, a trappable error occurs.

The value of the Bookmark property isn't the same as a record number.


Bookmarkable Property (DAO)

Bookmarkable Property

Returns a value that indicates whether a CdbRecordset object supports bookmarks, which you can set by using the Bookmark property.

Syntax

BOOLGetBookmarkable(VOID);

Remarks

Verify that the Bookmarkable property of a CdbRecordset object is True before you attempt to set or check the Bookmark property.

For CdbRecordset objects based entirely on Microsoft Jet tables, the value of the Bookmarkable property is True, and you can use bookmarks. Other database products may not support bookmarks, however. For example, you can't use bookmarks in any CdbRecordset object based on a linked Paradox table that has no primary key.


CacheSize Property (DAO)

CacheSize Property

Sets or returns the number of records retrieved from an ODBC data source that will be cached locally.

Syntax

VOIDSetCacheSize(LONG lSize);

LONGGetCacheSize(VOID);

Parameters

Type | Argument | Description
LONG | lSize | A Long between 5 and 1200 (limited by available memory) which specifies the number of records that will be cached locally. A typical value is 100. A setting of 0 turns off caching.

Remarks

Data caching improves performance if you use CdbRecordset objects to retrieve data from a remote server. A cache is a space in local memory that holds the data most recently retrieved from the server; this is useful if users request the data again while the application is running. When users request data, the Microsoft Jet database engine checks the cache for the requested data first rather than retrieving it from the server, which takes more time. The cache only saves data that comes from an ODBC data source.

Any Microsoft Jet-connected ODBC data source, such as a linked table, can have a local cache. To create the cache, open a CdbRecordset object from the remote data source, set the CacheSize and CacheStart properties, and then use the FillCache method, or step through the records by using the Move methods.

An ODBCDirect workspace can use a local cache. To create the cache, set the CacheSize property on a CdbQueryDef object. On a CdbRelation object, CacheSize is read-only and depends on the value of the CdbQueryDef object's CacheSize property. You can't use the CacheStart property on the FillCache method in an ODBCDirect workspace.

You can base the CacheSize property setting on the number of records your application can handle at one time. For example, if you're using a CdbRecordset object as the source of the data to be displayed on screen, you could set its CacheSize property to 20 to display 20 records at one time.

The Microsoft Jet database engine requests records within the cache range from the cache, and it requests records outside the cache range from the server.

Records retrieved from the cache don't reflect concurrent changes that other users made to the source data.

To force an update of all the cached data, set the CacheSize property of the CdbRecordset object to 0, re-set it to the size of the cache you originally requested, and then use the FillCache method.


CacheStart Property (DAO)

CacheStart Property

Sets or returns a value that specifies the bookmark of the first record in a dynaset-type CdbRecordset object containing data to be locally cached from an ODBC data source (Microsoft Jet workspaces only).

Syntax

VOIDSetCacheStart(CdbBookmark & pbm);

CdbBookmarkGetCacheStart(VOID);

Parameters

Type | Argument | Description
CdbBookmark & | pbm | A Bookmark reference of the first record to be cached.

Remarks

Data caching improves the performance of an application that retrieves data from a remote server through dynaset-type CdbRecordset objects. A cache is a space in local memory that holds the data most recently retrieved from the server in the event that the data will be requested again while the application is running. When data is requested, the Microsoft Jet database engine checks the cache for the requested data first rather than retrieving it from the server, which takes more time. Only data from an ODBC data source can be saved in the cache.

Any Microsoft Jet-connected ODBC data source, such as a linked table, can have a local cache. To create the cache, open a CdbRecordset object from the remote data source, set the CacheSize and CacheStart properties, and then use the FillCache method or step through the records using the Move methods.

The CacheStart property setting is the bookmark of the first record in the CdbRecordset object to be cached. You can use the bookmark of any record to set the CacheStart property. Make the record you want to start the cache the current record, and set the CacheStart property equal to the Bookmark property.

The Microsoft Jet database engine requests records within the cache range from the cache and it requests records outside the cache range from the server.

Records retrieved from the cache don't reflect changes made concurrently to the source data by other users.

To force an update of all the cached data, set the CacheSize property of the CdbRecordset object to 0, set it to the size of the cache you originally requested, and then use the FillCache method.


Clustered Property (DAO)

Clustered Property

Sets or returns a value that indicates whether a CdbIndex object represents a clustered index for a table (Microsoft Jet workspaces only).

Syntax

VOIDSetClustered(BOOL bFlag);

BOOLGetClustered(VOID);

Parameters

Type | Argument | Description
BOOL | bFlag | TRUE if the CdbIndex object represents a clustered index.

Remarks

Some IISAM desktop database formats use clustered indexes. A clustered index consists of one or more nonkey fields that, taken together, arrange all records in a table in a predefined order. A clustered index provides efficient access to records in a table in which the index values may not be unique.

The Clustered property is read/write for a new CdbIndex object not yet appended to a collection and read-only for an existing CdbIndex object in an Indexes collection.

Notes

  • Microsoft Jet databases ignore the Clustered property because the Microsoft Jet database engine doesn't support clustered indexes.

  • For ODBC data sources the Clustered property always returns False; it does not detect whether or not the ODBC data source has a clustered index.


CollatingOrder Property (DAO)

CollatingOrder Property

Returns a value that specifies the sequence of the sort order in text for string comparison or sorting (Microsoft Jet workspaces only).

Syntax

LONGGetCollatingOrder(VOID);

Remarks

The CollatingOrder property can be one of the following constants.

Constant | Sort order
dbSortGeneral | General (English, French, German, Portuguese, Italian, and Modern Spanish)
dbSortArabic | Arabic
dbSortChineseSimplified | Simplified Chinese
dbSortChineseTraditional | Traditional Chinese
dbSortCyrillic | Russian
dbSortCzech | Czech
dbSortDutch | Dutch
dbSortGreek | Greek
dbSortHebrew | Hebrew
dbSortHungarian | Hungarian
dbSortIcelandic | Icelandic
dbSortJapanese | Japanese
dbSortKorean | Korean
dbSortNeutral | Neutral
dbSortNorwDan | Norwegian or Danish
dbSortPDXIntl | Paradox International
dbSortPDXNor | Paradox Norwegian or Danish
dbSortPDXSwe | Paradox Swedish or Finnish
dbSortPolish | Polish
dbSortSlovenian | Slovenian
dbSortSpanish | Spanish
dbSortSwedFin | Swedish or Finnish
dbSortThai | Thai
dbSortTurkish | Turkish
dbSortUndefined | Undefined or unknown

The availability of the CollatingOrder property depends on the object that contains the Fields collection, as shown in the following table.

If the Fields collection belongs to a | Then CollatingOrder is
CdbIndex object | Not supported
CdbQueryDef object | Read-only
CdbRecordset object | Read-only
CdbRelation object | Not supported
CdbTableDef object | Read-only

The CollatingOrder property setting corresponds to the locale argument of the CreateDatabase method when the database was created or the CompactDatabase method when the database was most recently compacted.

Check the CollatingOrder property setting of a CdbDatabase or CdbField object to determine the string comparison method for the database or field. You can set the CollatingOrder property of a new, unappended CdbField object if you want the setting of the CdbField object to differ from that of the CdbDatabase object that contains it.

The CollatingOrder and Attributes property settings of a CdbField object in a Fields collection of a CdbIndex object together determine the sequence and direction of the sort order in an index. However, you can't set a collating order for an individual index—you can only set it for an entire table.


CollectionIndex Property (dbDAO)

CollectionIndex Property

Returns the position of a Field within its Fields collection, as indicated by a 0-based integer.

Syntax

SHORT GetCollectionIndex(VOID);

Remarks

A Field object in the Fields collection can be accessed by specifying its index. This property performs the inverse operation: the CollectionIndex property of a Field object yields its index in the collection.

Adding or deleting a Field will change the indexes of the other Field objects in the collection.


ConflictTable Property (DAO)

ConflictTable Property

Returns the name of a conflict table containing the database records that conflicted during the synchronization of two replicas (Microsoft Jet workspaces only).

Syntax

CStringGetConflictTable(VOID);

Remarks

If two users at two separate replicas each make a change to the same record in the database, the changes made by one user will fail to be applied to the other replica. Consequently, the user with the failed change must resolve the conflicts.

Conflicts occur at the record level, not between fields. For example, if one user changes the Address field and another updates the Phone field in the same record, then one change is rejected. Because conflicts occur at the record level, the rejection occurs even though the successful change and the rejected change are unlikely to result in a true conflict of information.

The synchronization mechanism handles the record conflicts by creating conflict tables, which contain the information that would have been placed in the table, if the change had been successful. You can examine these conflict tables and work through them row by row, fixing whatever is appropriate.

All conflict tables are named table_conflict, where table is the original name of the table, truncated to the maximum table name length.

A zero-length string is returned if there is no conflict table or the database isn't a replica.


Connect Property (DAO)

Connect Property

Sets or returns a value that provides information about the source of an open connection, an open database, a database used in a pass-through query, or a linked table. For CdbDatabase objects, new CdbConnection objects, linked tables, and CdbTableDef objects not yet appended to a collection, this property setting is read/write. For CdbQueryDef objects and base tables, this property is read-only.

Syntax

VOIDSetConnect(LPCTSTR pstrConnect);

CStringGetConnect(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstrConnect | A pointer to a string that specifies additional parameters to pass to ODBC or installable ISAM drivers. Use semicolons to separate parameters.

Remarks

The Connect property setting is a string composed of a database type specifier and zero or more parameters separated by semicolons. The Connect property passes additional information to ODBC and certain ISAM drivers as needed.

To perform an SQL pass-through query on a table linked to your Microsoft Jet database (.mdb) file, you must first set the Connect property of the linked table's database to a valid ODBC connection string.

For a CdbTableDef object that represents a linked table, the Connect property setting consists of one or two parts (a database type specifier and a path to the database), each of which ends with a semicolon.

The path as shown in the following table is the full path for the directory containing the database files and must be preceded by the identifier DATABASE=. In some cases (as with Microsoft Excel and Microsoft Jet databases), you should include a specific file name in the database path argument.

The following table shows possible database types and their corresponding database specifiers and paths for the Connect property setting. You can also specify “FTP://path/etc.” or “HTTP://path/etc.” For the path. In an ODBCDirect workspace, only the "ODBC" specifier can be used.

Database type | Specifier | Example
Microsoft Jet Database | [database]; | drive:\path\filename.mdb
dBASE III | dBASE III; | drive:\path
dBASE IV | dBASE IV; | drive:\path
dBASE 5 | dBASE 5.0; | drive:\path
Paradox 3.x | Paradox 3.x; | drive:\path
Paradox 4.x | Paradox 4.x; | drive:\path
Paradox 5.x | Paradox 5.x; | drive:\path
FoxPro 2.0 | FoxPro 2.0; | drive:\path
FoxPro 2.5 | FoxPro 2.5; | drive:\path
FoxPro 2.6 | FoxPro 2.6; | drive:\path
Excel 3.0 | Excel 3.0; | drive:\path\filename.xls
Excel 4.0 | Excel 4.0; | drive:\path\filename.xls
Excel 5.0 or Excel 95 | Excel 5.0; | drive:\path\filename.xls
Excel 97 | Excel 97; | drive:\path\filename.xls
HTML Import | HTML Import; | drive:\path\filename
HTML Export | HTML Export; | drive:\path
Text | Text; | drive:\path
ODBC ODBC;
DATABASE=database;
UID=user;
PWD=password;
DSN= datasourcename;
[LOGINTIMEOUT=seconds;] 		None
Exchange Exchange;
MAPILEVEL=folderpath; [TABLETYPE={ 01 }];[PROFILE=profile;]
[PWD=password;]
[DATABASE=database;] 		drive:\path\filename.mdb

If the specifier is only "ODBC;", the ODBC driver displays a dialog box listing all registered ODBC data source names so that the user can select a database.

If a password is required but not provided in the Connect property setting, a login dialog box is displayed the first time a table is accessed by the ODBC driver and again if the connection is closed and reopened.

For data in Microsoft Exchange, the required MAPILEVEL key should be set to a fully-resolved folder path (for example, "Mailbox - Pat SmithIAlpha/Today"). The path does not include the name of the folder that will be opened as a table; that folder’s name should instead be specified as the name argument to the CreateTable method. The TABLETYPE key should be set to "0" to open a folder (default) or "1" to open an address book. The PROFILE key defaults to the profile currently in use.

For base tables in a Microsoft Jet database (.mdb), the Connect property setting is a zero-length string ("").

You can set the Connect property for a CdbDatabase object by providing a source argument to the OpenDatabase method. You can check the setting to determine the type, path, user ID, password, or ODBC data source of the database.

On a CdbQueryDef object in a Microsoft Jet workspace, you can use the Connect property with the ReturnsRecords property to create an ODBC SQL pass-through query. The databasetype of the connection string is "ODBC;", and the remainder of the string contains information specific to the ODBC driver used to access the remote data. For more information, see the documentation for the specific driver.

Notes

  • You must set the Connect property before you set the ReturnsRecords property.

  • You must have access permissions to the computer that contains the database server you're trying to access.


Connection Property (DAO)

Connection Property

On a CdbDatabase object, returns the CdbConnection object that corresponds to the database (ODBCDirect workspaces only). This property is read-only for CdbDatabase.

On a CdbRecordset object, returns the CdbConnection object that owns the Recordset (ODBCDirect workspaces only). This property is read/write for CdbRecordset.

Syntax

CdbConnectionGetConnection(VOID);

Remarks

On a CdbDatabase object, use the Connection property to obtain a reference to a CdbConnection object that corresponds to the CdbDatabase. In DAO, a CdbConnection object and its corresponding CdbDatabase object are simply two different object variable references to the same object. The Database property of a CdbConnection object and the Connection property of a CdbDatabase object make it easier to change connections to an ODBC data source through the Microsoft Jet database engine to use ODBCDirect.


Container Property (DAO)

Container Property

Returns the name of the CdbContainer object to which a CdbDocument object belongs (Microsoft Jet workspaces only).

Syntax

CStringGetContainer(VOID);

Remarks

The return value is a string, containing the name of a CdbContainer object.


Count Property (DAO)

Count Property

Returns the number of objects in a collection.

Syntax

LONG collection.GetCount(VOID);

The collection placeholder is an object variable that represents a persistent collection.

Remarks

Because members of a collection begin with 0, you should always code loops starting with the 0 member and ending with the value of the Count property minus 1.

If the value of the Count property is 0, there are no objects in the collection.


Database Property (DAO)

Database Property

Returns the CdbDatabase object that corresponds to this connection (ODBCDirect workspaces only).

Syntax

CdbDatabaseGetDatabase(VOID);

Remarks

On a CdbConnection object, use the Database property to obtain a reference to a CdbDatabase object that corresponds to the CdbConnection. In DAO, a CdbConnection object and its corresponding CdbDatabase object are simply two different object variable references to the same object. The Database property of a CdbConnection object and the Connection property of a CdbDatabase object make it easier to change connections to an ODBC data source through the Microsoft Jet database engine to use ODBCDirect.


DataUpdatable Property (DAO)

DataUpdatable Property

Returns a value that indicates whether the data in the field represented by a Field object is updatable.

Syntax

BOOLGetDataUpdatable(VOID);

Remarks

Use this property to determine whether you can change the Value property setting of a CdbField object. This property is always False on a CdbField object whose Attributes property is dbAutoIncrField.

You can use the DataUpdatable property on CdbField objects that are appended to the Fields collection of CdbQueryDef, CdbRecordset, and CdbRelation objects, but not the Fields collection of CdbIndex or CdbTableDef objects.


DateCreated, LastUpdated Properties (DAO)

DateCreated, LastUpdated Properties

  • DateCreated returns the date and time that an object was created, or the date and time a base table was created if the object is a table-type CdbRecordset object (Microsoft Jet workspaces only).

  • LastUpdated returns the date and time of the most recent change made to an object, or to a base table if the object is a table-type CdbRecordset object (Microsoft Jet workspaces only).

Syntax

COleDateTimeGetDateCreated(VOID);

COleDateTimeGetLastUpdated(VOID);

Remarks

For table-type CdbRecordset objects, the date and time settings are derived from the computer on which the base table was created or last updated. For other objects, DateCreated and LastUpdated return the date and time that the object was created or last updated. In a multiuser environment, users should get these settings directly from the file server to avoid discrepancies in the DateCreated and LastUpdated property settings.


DefaultCursorDriver Property (DAO)

DefaultCursorDriver Property

Sets or returns the type of cursor driver used on the connection created by the OpenConnection or OpenDatabase methods (ODBCDirect workspaces only).

Syntax

LONGGetDefaultCursorDriver(VOID);

VOIDSetDefaultCursorDriver(LONG lDriverType);

Parameters

Type | Argument | Description
LONG | lDriverType | An integer specifying the type of cursor driver to use as described in Remarks.

Remarks

This property setting only affects connections established after the property has been set. Changing the DefaultCursorDriver property has no effect on existing connections.

The property can be set to one of the following constants:

Constant | Description
dbUseDefaultCursor | (Default) Uses server-side cursors if the server supports them; otherwise use the ODBC Cursor Library.
dbUseODBCCursor | Always uses the ODBC Cursor Library. This option provides better performance for small result sets, but degrades quickly for larger result sets.
dbUseServerCursor | Always uses server-side cursors. For most large operations this option provides better performance, but might cause more network traffic.
dbUseClientBatchCursor | Always uses the client batch cursor library. This option is required for batch updates.
dbUseNoCursor | Opens all cursors (that is, CdbRecordset objects) as forward-only type, read-only, with a rowset size of 1. Also known as "cursorless queries."


DefaultType Property (DAO)

DefaultType Property

Sets or returns a value that indicates what type of workspace (Microsoft Jet or ODBCDirect) will be used by the next CdbWorkspace object created.

Syntax

VOIDSetDefaultType(LONG lDefaultType);

LONGGetDefaultType(VOID);

Parameters

Type | Argument | Description
LONG | lDefaultType | An integer specifying the type of database engine to use as described in Remarks.

Remarks

This property can be either of the following constants:

Constant | Description
dbUseJet | Creates CdbWorkspace objects connected to the Microsoft Jet database engine.
dbUseODBC | Creates CdbWorkspace objects connected to an ODBC data source.

The setting can be overridden for a single CdbWorkspace by setting the lType argument to the CreateWorkspace method.


DefaultUser, DefaultPassword Properties (DAO)

DefaultUser, DefaultPassword Properties

  • DefaultUser sets the user name used to create the default CdbWorkspace when it is initialized.

  • DefaultPassword sets the password used to create the default CdbWorkspace when it is initialized.

Syntax: SetDefaultUser

VOIDSetDefaultUser(LPCTSTR pstr);

Parameters

Type | Argument | Description
LPCTSTR | pstr | A pointer to a string containing the user name. The setting for user name can be 1–20 characters long and can include alphabetic characters, accented characters, numbers, spaces, and symbols except for quotation marks ("), forward slash (/), backslash (\), brackets ([ ]), colon (:), pipe (|), less-than sign (<), greater-than sign (>), plus sign (+), equal sign (=), semicolon (;), comma (,), question mark (?), asterisk (*), leading spaces, and control characters (ASCII 00 to ASCII 31).

Syntax: SetDefaultPassword

VOIDSetDefaultPassword(LPCTSTR pstr);

Parameters

Type | Argument | Description
LPCTSTR | pstr | A pointer to a string containing a password. It can be up to 14 characters long and contain any character except ASCII 0.

Remarks

By default, the DefaultUser property is set to "admin" and the DefaultPassword property is set to a zero-length string ("").

User names aren't usually case-sensitive; however, if you're re-creating a user account that was deleted or created in a different workgroup, the user name must be an exact case-sensitive match of the original name. Passwords are case-sensitive.

Typically, you use the CreateWorkspace method to create a CdbWorkspace object with a given user name and password. However, for backward compatibility with earlier versions and for convenience when you don't implement a secured database, the Microsoft Jet database engine automatically creates a default CdbWorkspace object when needed if one isn't already open. In this case, the DefaultUser and DefaultPassword property values define the user and password for the default CdbWorkspace object.

For this property to take effect, you should set it before calling any DAO methods.


DefaultValue Property (DAO)

DefaultValue Property

Sets or returns the default value of a CdbField object. For a CdbField object not yet appended to the Fields collection, this property is read/write (Microsoft Jet workspaces only).

Syntax

VOIDSetDefaultValue(LPCTSTR pstr );

CStringGetDefaultValue(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstr | A pointer to a string that contains a maximum of 255 characters. It can be either text or an expression. If the property setting is an expression, it can't contain user-defined functions, Microsoft Jet database engine SQL aggregate functions, or references to queries, forms, or other CdbField objects.

Remarks

The availability of the DefaultValue property depends on the object that contains the Fields collection, as shown in the following table.

If the Fields collection belongs to a | Then DefaultValue is
CdbIndex object | Not supported
CdbQueryDef object | Read-only
CdbRecordset object | Read-only
CdbRelation object | Not supported
CdbTableDef object | Read/write

When a new record is created, the DefaultValue property setting is automatically entered as the value for the field. You can change the field value by setting its Value property.

Note You can also set the DefaultValue property of a CdbField object on a CdbTableDef object to a special value called "GenUniqueID( )". This causes a random number to be assigned to this field whenever a new record is added or created, thereby giving each record a unique identifier. The field's Type property must be Long.

The DefaultValue property doesn't apply to AutoNumber and Long Binary fields.


Description Property (DAO)

Description Property

Returns a descriptive string associated with an error.

Syntax

CStringGetDescription(VOID);

Remarks

The Description property comprises a short description of the error. Use this property to alert the user about an error that you cannot or do not want to handle.


DesignMasterID Property (DAO)

DesignMasterID Property

Sets or returns a 16-byte GUID that uniquely identifies the Design Master in a replica set (Microsoft Jet workspaces only).

Syntax

VOIDSetDesignMasterID(LPCTSTR pstrMasterID);

CStringGetDesignMasterID(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstrMasterID | A pointer to a string that contains the 16-byte GUID of a Design Master.

Remarks

You should set the DesignMasterID property only if you need to move the current Design Master. Setting this property makes a specific replica in the replica set the Design Master.

Caution Never create a second Design Master in a replica set. The existence of a second Design Master can result in the loss of data.

Under extreme circumstances — for example, if the Design Master is erased or corrupted — you can set this property at the current replica. However, setting this property at a replica when there is already another Design Master in the set might partition your replica set into two irreconcilable sets and prevent any further synchronization of data.

If you decide to make a replica of the new Design Master for the set, synchronize it with all the replicas in the replica set before setting the DesignMasterID property in the replica. The replica must be open in exclusive mode in order to make it the Design Master.

If you make a replica that is designated read-only into the Design Master, the target replica is made read/write; the old Design Master also remains read/write.

The DesignMasterID property setting is stored in the MSysRepInfo system table.


Direction Property (DAO)

Direction Property

Sets or returns a value that indicates whether a CdbParameter object represents an input parameter, an output parameter, both, or the return value from the procedure (ODBCDirect workspaces only).

Syntax

VOIDSetDirection(SHORT i);

SHORTGetDirection(VOID);

Parameters

Type | Example | Description
SHORT | i | A Short with one of the values shown in Remarks.

Remarks

The Direction property can be any of the following constants:

Constant | Description
dbParamInput | (Default) Passes information to the procedure.
dbParamInputOutput | Passes information both to and from the procedure.
dbParamOutput | Returns information from the procedure as in an output parameter in SQL.
dbParamReturnValue | Passes the return value from a procedure.

Use the Direction property to determine whether the parameter is an input parameter, output parameter, both, or the return value from the procedure. Some ODBC drivers do not provide information on the direction of parameters to a SELECT statement or procedure call. In these cases, it is necessary to set the direction prior to executing the query.

For example, the following procedure returns a value from a stored procedure named "get_employees":

{? = call get_employees}

This call produces one parameter — the return value. You need to set the direction of this parameter to dbParamOutput or dbParamReturnValue before executing the CdbQueryDef.

You need to set all parameter directions except dbParamInput before accessing or setting the values of the parameters and before executing the CdbQueryDef.

You should use dbParamReturnValue for return values, but in cases where that option is not supported by the driver or the server, you can use dbParamOutput instead.

Note The Microsoft SQL Server 6.0 driver automatically sets the Direction property for all procedure parameters. Not all ODBC drivers can determine the direction of a query parameter. In these cases, it is necessary to set the direction prior to executing the query.


DistinctCount Property (DAO)

DistinctCount Property

Returns a value that indicates the number of unique values for the CdbIndex object that are included in the associated table (Microsoft Jet workspaces only).

Syntax

LONGGetDistinctCount(VOID);

Remarks

Check the DistinctCount property to determine the number of unique values, or keys, in an index. Any key is counted only once, even though there may be multiple occurrences of that value if the index permits duplicate values. This information is useful in applications that attempt to optimize data access by evaluating index information. The number of unique values is also known as the cardinality of an CdbIndex object.

The DistinctCount property won't always reflect the actual number of keys at a particular time. For example, a change caused by a rolled back transaction won't be reflected immediately in the DistinctCount property. The DistinctCount property value also may not reflect the deletion of records with unique keys. The number will be accurate immediately after you use the CreateIndex method.


EditMode Property (DAO)

EditMode Property

Returns a value that indicates the state of editing for the current record.

Syntax

SHORTGetEditMode(VOID);

Remarks

The return value indicates the state of editing, as listed in the following table.

Constant | Description
dbEditNone | No editing operation is in progress.
dbEditInProgress | The Edit method has been invoked, and the current record is in the copy buffer.
dbEditAdd | The AddNew method has been invoked, and the current record in the copy buffer is a new record that hasn't been saved in the database.

The EditMode property is useful when an editing process is interrupted, for example, by an error during validation. You can use the value of the EditMode property to determine whether you should use the Update or CancelUpdate method.

You can also check to see if the LockEdits property setting is True and the EditMode property setting is dbEditInProgress to determine whether the current page is locked.


Filter Property (DAO)

Filter Property

Sets or returns a value that determines the records included in a subsequently opened CdbRecordset object (Microsoft Jet workspaces only).

Syntax

CStringGetFilter(VOID);

VOIDSetFilter(LPCTSTR pstr );

Parameters

Type | Argument | Description
LPCTSTR | pstr | A pointer to a string that contains the WHERE clause of an SQL statement without the reserved word WHERE.

Remarks

Use the Filter property to apply a filter to a dynaset-, snapshot-, or forward-only–type CdbRecordset object.

You can use the Filter property to restrict the records returned from an existing object when a new CdbRecordset object is opened based on an existing CdbRecordset object.

In many cases, it's faster to open a new CdbRecordset object by using an SQL statement that includes a WHERE clause.

Use the U.S. date format (month-day-year) when you filter fields containing dates, even if you're not using the U.S. version of the Microsoft Jet database engine (in which case you must assemble any dates by concatenating strings, for example, CString strFilter = strMonth + "-" + strDay + "-" + strYear;). Otherwise, the data may not be filtered as you expect.

If you set the property to a string concatenated with a non-integer value, and the system parameters specify a non-U.S. decimal character such as a comma (for example, CString strFilter = "PRICE > " + strPrice and strPrice = 125,50), an error occurs when you try to open the next CdbRecordset. This is because during concatenation, the number will be converted to a string using your system's default decimal character, and Microsoft Jet SQL only accepts U.S. decimal characters.


Foreign Property (DAO)

Foreign Property

Indicates whether a CdbIndex object represents a foreign key in a table (Microsoft Jet workspaces only).

Syntax

BOOLGetForeign(VOID);

Remarks

Returns True if the CdbIndex object represents a foreign key.

A foreign key consists of one or more fields in a foreign table that uniquely identify all rows in a primary table.

The Microsoft Jet database engine creates a CdbIndex object for the foreign table and sets the Foreign property when you create a relationship that enforces referential integrity.


ForeignName Property (DAO)

ForeignName Property

Sets or returns a value that specifies the name of the CdbField object in a foreign table that corresponds to a field in a primary table for a relationship (Microsoft Jet workspaces only).

Syntax

VOIDSetForeignName(LPCTSTR pstr );

CStringGetForeignName(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstr | A pointer to a string that contains the name of the field in a foreign table.

Remarks

Only a CdbField object that belongs to the Fields collection of a CdbRelation object can support the ForeignName property.

If the CdbRelation object isn't appended to the CdbDatabase, but the CdbField is appended to the CdbRelation object, the ForeignName property is read/write. Once the CdbRelation object is appended to the database, the ForeignName property is read-only.

The Name and ForeignName property settings for a CdbField object specify the names of the corresponding fields in the primary and foreign tables of a relationship. The Table and ForeignTable property settings for a CdbRelation object determine the primary and foreign tables of a relationship.

For example, if you had a list of valid part codes (in a field named PartNo) stored in a ValidParts table, you could establish a relationship with an OrderItem table such that if a part code were entered into the OrderItem table, it would have to already exist in the ValidParts table. If the part code didn't exist in the ValidParts table and you had not set the Attributes property of the CdbRelation object to dbRelationDontEnforce, a trappable error would occur.

In this case, the ValidParts table is the foreign table, so the ForeignTable property of the CdbRelation object would be set to ValidParts and the Table property of the CdbRelation object would be set to OrderItem. The Name and ForeignName properties of the CdbField object in the CdbRelation object's Fields collection would be set to PartNo.

The following illustration depicts the relation described above.


ForeignTable Property (DAO)

ForeignTable Property

Sets or returns the name of the foreign table in a relationship (Microsoft Jet workspaces only).

Syntax

VOIDSetForeignTable(LPCTSTR pstr );

CStringGetForeignTable(VOID);

Parameters

Type |  | Argument |  | Description
LPCTSTR | pstr |  | A pointer to a string that contains the name of the foreign table.

Remarks

The ForeignTable property setting of a CdbRelation object is the Name property setting of the CdbTableDef or CdbQueryDef object that represents the foreign table or query; the Table property setting is the Name property setting of the CdbTableDef or CdbQueryDef object that represents the primary table or query.

For example, if you had a list of valid part codes (in a field named PartNo) stored in a ValidParts table, you could establish a relationship with an OrderItem table such that if a part code were entered into the OrderItem table, it would already have to be in the ValidParts table. If the part code didn't exist in the ValidParts table and you had not set the Attributes property of the CdbRelation object to dbRelationDontEnforce, a trappable error would occur.

In this case, the ValidParts table is the primary table, so the Table property of the CdbRelation object would be set to ValidParts and the ForeignTable property of the CdbRelation object would be set to OrderItem. The Name and ForeignName properties of the CdbField object in the CdbRelation object's Fields collection would be set to PartNo.

The following illustration depicts the relation described above.

This property is read/write for a new CdbRelation object not yet appended to a collection and read-only for an existing CdbRelation object in the Relations collection.


HelpContext, HelpFile Properties (DAO)

HelpContext, HelpFile Properties

  • HelpContext returns a context ID, as a Long variable, for a topic in a Microsoft Windows Help file.

  • HelpFile returns a String that is a fully qualified path to the Help file.

Syntax: HelpContext

LONGGetHelpContext(VOID);

Syntax: HelpFile

CStringGetHelpFile(VOID);

Remarks

If you specify a Microsoft Windows Help file in HelpFile, you can use the HelpContext property to automatically display the Help topic it identifies.

Note You should write procedures in your application to handle typical errors. When programming with an object, you can use the Help supplied by the object's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error is not recoverable.


IgnoreNulls Property (DAO)

IgnoreNulls Property

Sets or returns a value that indicates whether records that have Null values in their index fields have index entries (Microsoft Jet workspaces only).

Syntax

VOIDSetIgnoreNulls(BOOL bFlag);

BOOLGetIgnoreNulls(VOID);

Parameters

Type | Argument | Description
BOOL | bFlag | TRUE if the fields with Null values don't have an index entry.

Remarks

To speed up the process of searching for records, you can define an index for a field. If you allow Null entries in an indexed field and expect many of the entries to be Null, you can set the IgnoreNulls property for the CdbIndex object to True to reduce the amount of storage space that the index uses.

This property is read/write for a new CdbIndex object not yet appended to a collection and read-only for an existing CdbIndex object in an Indexes collection.

The IgnoreNulls property setting and the Required property setting together determine whether a record with a Null index value has an index entry.

If IgnoreNulls is | And Required is | Then a Null Value is
True | False | Allowed in the index field; no index entry added.
False | False | Allowed in the index field; index entry added.
True or False | True | Not allowed in the index field; no index entry added.


Index Property (DAO)

Index Property

Sets or returns a value that indicates the name of the current CdbIndex object in a table-type CdbRecordset object (Microsoft Jet workspaces only).

Syntax

VOIDSetIndex(LPCTSTR pstr );

CStringGetIndex(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstr | A string containing the name of a CdbIndex object.

Remarks

Records in base tables aren't stored in any particular order. Setting the Index property changes the order of records returned from the database; it doesn't affect the order in which the records are stored.

The specified CdbIndex object must already be defined. If you set the Index property to a CdbIndex object that doesn't exist or if the Index property isn't set when you use the Seek method, a trappable error occurs.

Examine the Indexes collection of a CdbTableDef object to determine what CdbIndex objects are available to table-type CdbRecordset objects created from that CdbTableDef object.

You can create a new index for the table by creating a new CdbIndex object, setting its properties, appending it to the Indexes collection of the underlying CdbTableDef object, and then reopening the CdbRecordset object.

Records returned from a table-type CdbRecordset object can be ordered only by the indexes defined for the underlying CdbTableDef object. To sort records in some other order, you can open a dynaset-, snapshot-, or forward-only–type CdbRecordset object by using an SQL statement with an ORDER BY clause.

Notes

  • You don't have to create indexes for tables. With large, unindexed tables, accessing a specific record or creating a CdbRecordset object can take a long time. On the other hand, creating too many indexes slows down update, append, and delete operations because all indexes are automatically updated.

  • Records read from tables without indexes are returned in no particular sequence.

  • The Attributes property of each CdbField object in the CdbIndex object determines the order of records and consequently determines the access techniques to use for that index.

  • A unique index helps optimize finding records.

  • Indexes don't affect the physical order of a base table—indexes affect only how the records are accessed by the table-type CdbRecordset object when a particular index is chosen or when CdbRecordset is opened.


Inherit Property (DAO)

Inherit Property

Sets or returns a value that indicates whether new CdbDocument objects will inherit a default Permissions property setting (Microsoft Jet workspaces only).

Syntax

VOIDSetInherit(BOOL bFlag);

BOOLGetInherit(VOID);

Parameters

Type | Argument | Description
BOOL | bFlag | If TRUE, CdbDocument objects inherit a default Permissions property setting.

Remarks

Use the Inherit property in conjunction with the Permissions property to define what permissions new documents will automatically have when they're created. If you set the Inherit property to True, and then set a permission on a container, then whenever a new document is created in that container, that permission will be set on the new document. This is a very convenient way of presetting permissions on an object.

Setting the Inherit property will not affect existing documents in the container—you can't modify all the permissions on all existing documents in a container by setting the Inherit property and a new permission. It will affect only new documents that are created after the Inherit property is set.


Inherited Property (DAO)

Inherited Property

Returns a value that indicates whether a CdbProperty object is inherited from an underlying object.

Syntax

BOOLGetInherited(VOID);

Remarks

You can use the Inherited property to determine whether a user-defined CdbProperty was created for the object it applies to or whether the CdbProperty was inherited from another object. For example, suppose you create a new CdbProperty for a CdbQueryDef object and then open a CdbRecordset object from the CdbQueryDef object. This new CdbProperty will be part of the CdbRecordset object's Properties collection, and its Inherited property will be set to True because the property was created for the CdbQueryDef object, not the CdbRecordset object.

For built-in CdbProperty objects that represent predefined properties, the only possible return value is False. This property is always False in an ODBCDirect workspace.


IniPath Property (DAO)

IniPath Property

Sets or returns information about the Windows Registry key that contains values for the Microsoft Jet database engine (Microsoft Jet workspaces only).

Syntax

VOIDSetIniPath(LPCTSTR pstr );

CStringGetIniPath(VOID);

Parameters

Type | Example | Description
LPCTSTR | pstr | Pointer to a string containing the user-supplied portion of the registry key.

Remarks

You can configure the Microsoft Jet engine with the Windows Registry. You can use the Registry to set options, such as installable ISAM DLLs.

For this option to have any effect, you must set the IniPath property before your application invokes any other DAO code. The scope of this setting is limited to your application and can't be changed without restarting your application.

You also use the Registry to provide initialization parameters for some installable ISAM database drivers. For example, to use Paradox version 4.0, set the IniPath property to a part of the Registry containing the appropriate parameters.

This property recognizes either HKEY_LOCAL_MACHINE or HKEY_LOCAL_USER. If no root key is supplied, the default is HKEY_LOCAL_MACHINE.

Microsoft Jet versions 2.5 or earlier kept initialization information in .ini files.


IsolateODBCTrans Property (DAO)

IsolateODBCTrans Property

Sets or returns a value that indicates whether multiple transactions that involve the same Microsoft Jet-connected ODBC data source are isolated (Microsoft Jet workspaces only).

Syntax

VOIDSetIsolateODBCTrans(BOOL bFlag);

BOOLGetIsolateODBCTrans(VOID);

Parameters

Type | Argument | Description
BOOL | bFlag | TRUEIsolate transactions involving the same ODBC connection. FALSE(Default) Allow multiple transactions involving the same ODBC connection.

Remarks

In some situations, you need to have multiple simultaneous transactions pending on the same ODBC connection. To do this, you need to open a separate CdbWorkspace for each transaction. Although each CdbWorkspace can have its own ODBC connection to the database, this slows system performance. Because transaction isolation isn't usually required, ODBC connections from multiple CdbWorkspace objects opened by the same user are shared by default.

Some ODBC servers, such as Microsoft SQL Server, don't allow simultaneous transactions on a single connection. If you need to have more than one transaction at a time pending against such a database, set the IsolateODBCTrans property to True on each CdbWorkspace as soon as you open it. This forces a separate ODBC connection for each CdbWorkspace.


KeepLocal Property (DAO)

KeepLocal Property

Sets or returns a value on a table, query, form, report, macro, or module that you do not want to replicate when the database is replicated (Microsoft Jet workspaces only).

Note Before getting or setting the KeepLocal property on a CdbDocument, CdbTableDef, or CdbQueryDef object, you must create it by using the CreateProperty method and append it to the Properties collection for the object.

Syntax

There is no member function to explicitly access this property. See Usage below for an example of how this property is managed.

Remarks

If you set this property to "T", the object will remain local when the database is replicated. You can't use the KeepLocal property on objects after they have been replicated.

Once you set the KeepLocal property, it will appear in the Properties collection for the object.

Before setting the KeepLocal property, you should check the value of the Replicable property.

After you make a database replicable, all new objects created within the Design Master, or in any other replicas in the set, are local objects. Local objects remain in the replica in which they're created and aren't copied throughout the replica set. Each time you make a new replica in the set, the new replica contains all the replicable objects from the source replica, but none of the local objects from the source replica.

If you create a new object in a replica and want to change it from local to replicable so that all users can use it, you can either create it in, or import it into, the Design Master. Be sure to delete the local object from any replicas; otherwise, you will encounter a design error. After the object is part of the Design Master, set the object's Replicable property to True.

The object on which you are setting the KeepLocal property might have already inherited that property from another object. However, the value set by the other object has no effect on the behavior of the object you want to keep local. You must explicitly set the property for each object.

Usage

...
CdbDBEngine      engine;
CdbProperty      prp;
CdbQueryDef      qdf;
COleVariant      vTrue(_T("T"));
...
// Initialize engine, queryDef, etc.
prp = qdf.CreateProperty(
            _T("Replicable"), dbText, &vTrue);
qdf.Properties.Append( prp );
...
prp = qdf.Properties[_T("Replicable")];
if (prp.GetValue() == vTrue)
   {
   prp = qdf.CreateProperty(
            _T("KeepLocal"), dbText, &vTrue);
   qdf.Properties.Append( prp );
   }
...


LastModified Property (DAO)

LastModified Property

Returns a bookmark indicating the most recently added or changed record.

Syntax

CdbBookmarkGetLastModified(VOID);

Remarks

You can use the LastModified property to move to the most recently added or updated record. Use the LastModified property with table- and dynaset-type CdbRecordset objects. A record must be added or modified in the CdbRecordset object itself in order for the LastModified property to have a value.


LockEdits Property (DAO)

LockEdits Property

Sets or returns a value indicating the type of locking that is in effect while editing.

Syntax

BOOLGetLockEdits(VOID);

VOIDSetLockEdits(BOOL bFlag);

Parameters

Type | Example | Description
BOOL | bFlag | TRUE(Default) Pessimistic locking is in effect. The 2K page containing the record you're editing is locked as soon as you use the Edit method. FALSEOptimistic locking is in effect for editing. The 2K page containing the record is not locked until the Update method is executed.

Remarks

You can use the LockEdits property with updatable CdbRecordset objects.

If a page is locked, no other user can edit records on the same page. If you set LockEdits to True and another user already has the page locked, an error occurs when you use the Edit method. Other users can read data from locked pages.

If you set the LockEdits property to False and later use the Update method while another user has the page locked, an error occurs. To see the changes made to your record by another user, use the Move method with 0 as the argument; however, if you do this, you will lose your changes.

When working with Microsoft Jet-connected ODBC data sources, the LockEdits property is always set to False, or optimistic locking. The Microsoft Jet database engine has no control over the locking mechanisms used in external database servers.

Note You can preset the value of LockEdits when you first open the CdbRecordset by setting the lLockEdits argument of the OpenRecordset method. Setting the lLockEdits argument to dbPessimistic will set the LockEdits property to True, and setting lLockEdits to any other value will set the LockEdits property to False.


LoginTimeout Property (DAO)

LoginTimeout Property

Sets or returns the number of seconds before an error occurs when you attempt to log on to an ODBC database.

Syntax

VOIDSetLoginTimeout(SHORT sTime);

SHORTGetLoginTimeout(VOID);

Parameters

Type | Argument | Description
SHORT | sTime | A short integer containing the number of seconds before a logon timeout error occurs. The default is 20.

Remarks

When you're attempting to log on to an ODBC database, such as Microsoft SQL Server, the connection can fail as a result of network errors or because the server isn't running. Rather than waiting for the default 20 seconds to connect, you can specify how long to wait before raising an error. Logging on to the server happens implicitly as part of a number of different events, such as running a query on an external server database.

The default LoginTimeout property setting is 20 seconds. When the LoginTimeout property is set to 0, no timeout occurs.

You can use LoginTimeout on the CdbDBEngine object in both Microsoft Jet and ODBCDirect workspaces. You can use LoginTimeout on the CdbWorkspace object only in ODBCDirect workspaces. Setting the property to -1 on a CdbWorkspace will default to the current setting of DBEngine.LoginTimeout. You can change this property in a Workspace at any time, and the new setting will take effect with the next CdbConnection or CdbDatabase object opened.

The default value is determined by the ODBC driver. In a Microsoft Jet workspace, you can override the driver’s default value by creating a new “ODBC” key in the Registry path \HKEY_LOCAL_MACHINE\SOFTWARE\Jet\3.5\, creating a LoginTimeout parameter in this key and setting the value as desired.


LogMessages Property (DAO)

LogMessages Property

Sets or returns a value that specifies if the messages returned from a Microsoft Jet-connected ODBC data source are recorded (Microsoft Jet workspaces only).

Note Before you can set or get the value of the LogMessages property, you must create the LogMessages property with the CreateProperty method and append it to the Properties collection of a CdbQueryDef object.

Syntax

There is no member function to explicitly access this property. See Usage below for an example of how this property is managed.

Remarks

Some pass-through queries can return messages in addition to data. If you set the LogMessages property to True, the Microsoft Jet database engine creates a table that contains returned messages. The table name is the user name concatenated with a hyphen (-) and a sequential number starting at 00. For example, because the default user name is Admin, the tables returned would be named Admin-00, Admin-01, and so on.

If you expect the query to return messages, create and append a user-defined LogMessages property for the CdbQueryDef object, and set its type to Boolean and its value to True.

Once you've processed the results from these tables, you may want to delete them from the database along with the temporary query used to create them.

Usage

...
CdbDBEngine      engine;
CdbProperty      prp;
CdbQueryDef      qdf;
COleVariant      vTrue((short)TRUE, VT_BOOL);
...
// Initialize engine, queryDef, etc.
prp = qdf.CreateProperty(
            _T("LogMessages"), dbBoolean, &vTrue);
qdf.Properties.Append( prp );
...


MaxRecords Property (DAO)

MaxRecords Property

Sets or returns the maximum number of records to return from a query.

Syntax

VOIDSetMaxRecords(LONG lRecords);

LONGGetMaxRecords(VOID);

Parameters

Type | Example | Description
LONG | lRecords | A Long specifying the maximum number of records to return.

Remarks

Once the number of rows specified by MaxRecords is returned to your application in a CdbRecordset, the query processor will stop returning additional records even if more records would qualify for inclusion in the CdbRecordset. This property is useful in situations where limited client resources prohibit management of large numbers of records.

The default value is 0, indicating no limit on the number of records returned.


Name Property (DAO)

Name Property

Sets or returns a user-defined name for a DAO object. For an object not appended to a collection, this property is read/write.

Syntax

VOIDSetName(LPCTSTR pstr );

StringGetName(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstr | A pointer to a string that contains the name of the object.

Remarks

The name must start with a letter. The maximum number of characters depends on the type of object Name applies to, as shown in Remarks. It can include numbers and underscore characters ( _ ) but can't include punctuation or spaces.

CdbTableDef, CdbQueryDef, CdbField, CdbIndex, CdbUser, and CdbGroup objects can't share the same name with any object in the same collection.

The Name property of a CdbRecordset object opened by using an SQL statement is the first 256 characters of the SQL statement.

Note For many of the DAO objects, the Name property reflects the name as known to the CdbDatabase object, as in the name of a CdbTableDef, CdbField, or CdbQueryDef object. There is no direct link between the name of the DAO object and the object variable used to reference it.

The read/write usage of the Name property depends on the type of object it applies to, and whether or not the object has been appended to a collection. In an ODBCDirect workspace, the Name property of an appended object is always read-only. The following table indicates whether the Name property in a Microsoft Jet workspace is read/write or read-only for an object that is appended to a collection (unless otherwise noted), and also indicates its maximum length in cases where it is read/write.

Object | Usage | Maximum length
CdbContainer | Read-only |
CdbConnection | Read-only |
CdbDatabase | Read-only |
CdbDocument | Read-only |
CdbField |  |
Unappended | Read/write | 64
Appended to CdbIndex | Read-only |
Appended to CdbQueryDef | Read-only |
Appended to CdbRecordset | Read-only |
Appended to CdbTableDef (native) | Read/write | 64
Appended to CdbTableDef (linked) | Read-only |
Appended to CdbRelation | Read-only |
CdbGroup |  |
Unappended | Read/write | 20
Appended | Read-only |
CdbIndex |  |
Unappended | Read/write | 64
Appended | Read-only |
CdbParameter | Read-only |
CdbProperty |  |
Unappended | Read/write | 64
Appended | Read-only |
Built-in | Read-only |
CdbQueryDef |  |
Unappended | Read/write | 64
Temporary | Read-only |
Appended | Read/write | 64
CdbRecordset | Read-only |
CdbRelation |  |
Unappended | Read/write | 64
Appended | Read-only |
CdbTableDef | Read/write | 64
CdbUser |  |
Unappended | Read/write | 20
Appended | Read-only |
CdbWorkspace |  |
Unappended | Read/write | 20
Appended | Read-only |


NoMatch Property (DAO)

NoMatch Property

Indicates whether a particular record was found by using the Seek method or one of the Find methods (Microsoft Jet workspaces only).

Syntax

BOOLGetNoMatch(VOID);

Remarks

To locate a record, use the Seek method on a table-type CdbRecordset object or one of the Find methods on a dynaset- or snapshot-type CdbRecordset object. Check the NoMatch property setting to see whether the record was found.

If the Seek or Find method is unsuccessful and the NoMatch property is True, the current record will no longer be valid. Be sure to obtain the current record's bookmark before using the Seek method or a Find method if you'll need to return to that record.

When you first open a CdbRecordset object, its NoMatch property is set to False.

Note Using any of the Move methods on a CdbRecordset object won't affect its NoMatch property setting.


Number Property (DAO)

Number Property

Returns a numeric value specifying an error. The Number property is the CdbError object's default property.

Syntax

LONGGetNumber(VOID);

Remarks

Use the Number property to determine the error that occurred. The value of the property corresponds to a unique trap number that corresponds to an error condition. For a complete list of all trap numbers and error conditions, see Trappable Microsoft Jet and DAO Errors.


ODBCTimeout Property (DAO)

ODBCTimeout Property

Indicates the number of seconds to wait before a timeout error occurs when a CdbQueryDef is executed on an ODBC database.

Syntax

VOIDSetODBCTimeout(SHORT sTime);

SHORTGetODBCTimeout(VOID);

Parameters

Type | Argument | Description
SHORT | sTime | A Short that contains number of seconds to wait before a timeout error occurs. When the ODBCTimeout property is set to 0, no timeout error occurs. When the ODBCTimeout property is set to -1, the timeout defaults to the current setting of the CdbQueryTimeout property of the CdbConnection or CdbDatabase object that contains the CdbQueryDef.

Remarks

When you're using an ODBC database, such as Microsoft SQL Server, delays can occur because of network traffic or heavy use of the ODBC server. Rather than waiting indefinitely, you can specify how long to wait before returning an error.

Setting the ODBCTimeout property of a CdbQueryDef object overrides the value specified by the QueryTimeout property of the CdbConnection or CdbDatabase object containing the CdbQueryDef, but only for that CdbQueryDef object.

Note In an ODBCDirect workspace, after setting ODBCTimeout to an explicit value you can reset it back to the default (that is, -1) only once during the life of the CdbQueryDef object. Otherwise, an error will occur.


OrdinalPosition Property (DAO)

OrdinalPosition Property

Sets or returns the relative position of a CdbField object within a Fields collection.

Syntax

VOIDSetOrdinalPosition(SHORT sPosition);

SHORTGetOrdinalPosition(VOID);

Parameters

Type | Argument | Description
SHORT | sPosition | A Short that specifies the numeric order of the field.

Remarks

The availability of the OrdinalPosition property depends on the object that contains the Fields collection, as shown in the following table.

If the Fields collection belongs to a | Then OrdinalPosition is
CdbIndex object | Not supported
CdbQueryDef object | Read-only
CdbRecordset object | Read-only
CdbRelation object | Not supported
CdbTableDef object | Read/write

For an object not yet appended to the Fields collection, this property is read/write and the default value is 0.

Generally, the ordinal position of an object that you append to a collection depends on the order in which you append the object. The first appended object is in the first position (0), the second appended object is in the second position (1), and so on. The last appended object is in ordinal position count – 1, where count is the number of objects in the collection as specified by the Count property setting.

You can use the OrdinalPosition property to specify an ordinal position for new CdbField objects that differs from the order in which you append those objects to a collection. This enables you to specify a field order for your tables, queries, and recordsets when you use them in an application. For example, the order in which fields are returned in a SELECT * query is determined by the current OrdinalPosition property values.

You can permanently reset the order in which fields are returned in recordsets by setting the OrdinalPosition property to any positive integer.

Two or more CdbField objects in the same collection can have the same OrdinalPosition property value, in which case they will be ordered alphabetically. For example, if you have a field named Age set to 4 and you set a second field named Weight to 4, Weight is returned after Age.

You can specify a number that is greater than the number of fields minus 1. The field will be returned in an order relative to the largest number. For example, if you set a field's OrdinalPosition property to 20 (and there are only 5 fields) and you've set the OrdinalPosition property for two other fields to 10 and 30, respectively, the field set to 20 is returned between the fields set to 10 and 30.

Note Even if the Fields collection of a CdbTableDef has not been refreshed, the field order in a CdbRecordset opened from the CdbTableDef will reflect the OrdinalPosition data of the CdbTableDef object. A table-type CdbRecordset will have the same OrdinalPosition data as the underlying table, but any other type of CdbRecordset will have new OrdinalPosition data (starting with 0) that follow the order determined by the OrdinalPosition data of the CdbTableDef.


OriginalValue Property (DAO)

OriginalValue Property

Returns the value of a Field in the database that existed when the last batch update began (ODBCDirect workspaces only).

Syntax

COleVariantGetOriginalValue(VOID);

Remarks

During an optimistic batch update, a collision may occur where a second client modifies the same field and record in between the time the first client retrieves the data and the first client's update attempt. The OriginalValue property contains the value of the field at the time the last batch Update began. If this value does not match the value actually in the database when the batch Update attempts to write to the database, a collision occurs. When this happens, the new value in the database will be accessible through the VisibleValue property.


Owner Property (DAO)

Owner Property

Sets or returns a value that specifies the owner of the object (Microsoft Jet workspaces only).

Syntax

VOIDSetOwner(LPCTSTR pstr );

CStringGetOwner(VOID);

Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that specifies the CdbUser or CdbGroup object that is the owner.

Remarks

The owner of an object has certain access privileges denied to other users. Any individual user account (represented by a CdbUser object) or group of user accounts (represented by a CdbGroup object) can change the Owner property setting at any time if it has the appropriate permissions.


PartialReplica Property (DAO)

PartialReplica Property

Sets or returns a value on a CdbRelation object indicating whether that relation should be considered when populating a partial replica from a full replica. (Microsoft Jet databases only.)

Syntax

VOIDSetPartialReplica(BOOL bFlag);

BOOLGetPartialReplica(VOID);

Parameters

Type | Argument | Description
BOOL | bFlag | TRUE when the relation should be enforced during synchronization.

Remarks

This property enables you to replicate data from the full replica to the partial replica based on relationships between tables. You can use the PartialReplica property when setting the ReplicaFilter property alone can't adequately specify what data should be replicated to the partial. For example, suppose you have a database in which the Customers table has a one-to-many relationship with the Orders table, and you want to configure a partial replica that only replicates orders from customers in the California region (instead of all orders). It is not possible to set the ReplicaFilter property on the Orders table to Region = 'CA' because the Region field is in the Customers table, not the Orders table.

To replicate all orders from the California region, you must indicate that the relation between the Orders and Customers tables will be active during replication. Once you've created a partial replica, the following steps will populate it with all orders from the California region:

  1. Set the ReplicaFilter property on the Customers CdbTableDef object to "Region = 'CA'".

  2. Set the value of the PartialReplica property to True on the CdbRelation object corresponding to the relationship between Orders and Customers.

  3. Invoke the PopulatePartial method.

Caution When you set a replica filter or replica relation, be aware that records in the partial replica that don't satisfy the restriction criteria will be removed from the partial replica, but not from the full replica. For example, suppose you set the ReplicaFilter property on the Customers TableDef in the partial replica to "Region = 'CA'" and you then repopulate the database. This will insert or update all records for California-based customers. If you then reset the ReplicaFilter property to "Region = 'FL'" and repopulate the database, all California region records in the partial replica will be removed, and all records from Florida-based customers will be inserted from the full replica. No records in the full replica will be deleted.

Before setting either the ReplicaFilter or PartialReplica property, it's a good idea to synchronize the partial replica in which you are setting these properties with the full replica. This will ensure that pending changes in the partial replica will be merged into the full replica before any records are removed in the partial replica.


Password Property (DAO)

Password Property

Sets the password for a user account (Microsoft Jet workspaces only).

Syntax

VOIDSetPassword(LPCTSTR pstr);

Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains up to 14 characters and can include any characters except the ASCII character 0 (null).

Remarks

Set the Password property along with the PID property when you create a new CdbUser object. This property is write-only for new objects not yet appended to a collection and is not available for existing objects.

Use the NewPassword method to change the Password property setting for an existing User object. To clear a password, set the newpassword argument of the NewPassword method to a zero-length string ("").

Passwords are case-sensitive.

Note If you don't have access permission, you can't change the password of any other user.


PercentPosition Property (DAO)

PercentPosition Property

Sets or returns a value indicating the approximate location of the current record in the CdbRecordset object based on a percentage of the records in the CdbRecordset.

Syntax

VOIDSetPercentPosition(FLOAT fPercent );

FLOATGetPercentPosition(VOID);

Parameters

Type | Argument | Description
FLOAT | fPercent | A Float between 0.0 and 100.00.

Remarks

To indicate or change the approximate position of the current record in a CdbRecordset object, you can check or set the PercentPosition property. When working with a dynaset- or snapshot-type CdbRecordset object opened directly from a base table, first populate the CdbRecordset object by moving to the last record before you set or check the PercentPosition property. If you use the PercentPosition property before fully populating the CdbRecordset object, the amount of movement is relative to the number of records accessed as indicated by the RecordCount property setting. You can move to the last record by using the MoveLast method.

Note Using the PercentPosition property to move the current record to a specific record in a CdbRecordset object isn't recommended?the Bookmark property is better suited for this task.

Once you set the PercentPosition property to a value, the record at the approximate position corresponding to that value becomes current and the PercentPosition property is reset to a value that reflects the approximate position of the current record. For example, if your CdbRecordset object contains only five records and you set its PercentPosition property value to 77, the value returned from the PercentPosition property may be 80, not 77.

The PercentPosition property applies to all types of CdbRecordset objects except for forward-only–type CdbRecordset objects or CdbRecordset objects opened from pass-through queries against remote databases.

You can use the PercentPosition property with a scroll bar on a form or text box to indicate the location of the current record in a CdbRecordset object.


Permissions Property (DAO)

Permissions Property

Sets or returns a value that establishes the permissions for the user or group identified by the UserName property of a CdbContainer or CdbDocument object (Microsoft Jet workspaces only).

Syntax

VOIDSetPermissions(LONG lPermissions);

LONGGetPermissions(VOID);

Parameters

Type | Example | Description
LONG | lPermissions | A Long that contains values as listed in Remarks.

Remarks

Use this property to establish or determine the type of read/write permission the user has for a CdbContainer or CdbDocument object.

The following tables list the valid constants for the Permissions property of various DAO objects. Unless otherwise noted, all constants shown in all tables are valid for CdbDocument objects as well.

For a CdbContainer object other than Tables and Databases containers, any of the following constants are available.

Constant | The User
dbSecNoAccess | Does not have access to the object (not valid for Document objects).
dbSecFullAccess | Has full access to the object.
dbSecDelete | Can delete the object.
dbSecReadSec | Can read the object's security-related information.
dbSecWriteSec | Can alter access permissions.
dbSecWriteOwner | Can change the Owner property setting.

For a CdbContainer object for the Tables container, any of the following constants are available.

Constant | The User Can
dbSecCreate | Create new documents (not valid for CdbDocument objects).
dbSecReadDef | Read the table definition, including column and index information.
dbSecWriteDef | Modify or delete the table definition, including column and index information.
dbSecRetrieveData | Retrieve data from the CdbDocument object.
dbSecInsertData | Add records.
dbSecReplaceData | Modify records.
dbSecDeleteData | Delete records.

For a CdbContainer object for the Databases container, any of the following constants are available.

Constant | The User
dbSecDBAdmin | Can replicate a database and change the database password (not valid for CdbDocument objects).
dbSecDBCreate | Can create new databases. This option is valid only on the Databases container in the workgroup information file (Systen.mdw). This constant isn't valid for CdbDocument objects.
dbSecDBExclusive | Has exclusive access to the database.
dbSecDBOpen | Can open the database.

Use this property to establish or determine the type of read/write permission the user has for a CdbContainer or CdbDocument object.

A CdbDocument object inherits the permissions for users from its CdbContainer object, provided the Inherit property of the CdbContainer object is set for those users or for a group to which the users belong. By setting a CdbDocument object's Permissions and UserName properties later, you can further refine the access control behavior of your object.

If you want to set or return permissions for a user that include permissions inherited from any groups to which the user belongs, use the AllPermissions property.


PID Property (DAO)

PID Property

Sets the personal identifier (PID) for either a group or a user account (Microsoft Jet workspaces only).

Syntax

VOIDSetPID(LPCTSTR pstr);

Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to string that contains 4–20 alphanumeric characters.

Remarks

Set the PID property along with the Name property when you create a new CdbGroup object. Set the PID property along with the Name and Password properties when you create a new CdbUser object.

This property is write-only for new objects not yet appended to a collection and is not available for existing objects.


Prepare Property (DAO)

Prepare Property

Sets or returns a value that indicates whether the query should be prepared on the server as a temporary stored procedure, using the ODBC SQLPrepare API function, prior to execution, or just executed using the ODBC SQLExecDirect API function (ODBCDirect workspaces only).

Syntax

VOIDSetPrepare(LPVARIANT pv);

COleVariantGetPrepare(VOID);

Parameters

Type | Argument | Description
LPVARIANT | pv | A pointer to a variant with one of the values shown below.

Remarks

This property takes either of the following constants:

Constant | Description
dbQPrepare | (Default) The statement is prepared (that is, the ODBC SQLPrepare API is called).
dbQUnprepare | The statement is not prepared (that is, the ODBC SQLExecDirect API is called).

You can use the Prepare property to either have the server create a temporary stored procedure from your query and then execute it, or just have the query executed directly. By default the Prepare property is set to dbQPrepare. However, you can set this property to dbQUnprepare to prohibit preparing of the query. In this case, the query is executed using the SQLExecDirect API.

Creating a stored procedure can slow down the initial operation, but increases performance of all subsequent references to the query. However, some queries cannot be executed in the form of stored procedures. In these cases, you must set the Prepare property to dbQUnprepare.

If Prepare is set to dbQPrepare, this can be overridden when the query is executed by setting the Execute method's options argument to dbExecDirect.

Note The ODBC SQLPrepare API is called as soon as the SQL property is set. Therefore, if you want to improve performance using the dbQUnprepare option, you must set the Prepare property before setting the SQL property.


Primary Property (DAO)

Primary Property

Sets or returns a value that indicates whether a CdbIndex object represents a primary index for a table (Microsoft Jet workspaces only).

Syntax

VOIDSetPrimary(BOOL bFlag);

BOOLGetPrimary(VOID);

Parameters

Type | Example | Description
BOOL | bFlag | TRUE if the CdbIndex object represents a primary index.

Remarks

A primary index consists of one or more fields that uniquely identify all records in a table in a predefined order. Because the index field must be unique, the Unique property of the CdbIndex object is set to True. If the primary index consists of more than one field, each field can contain duplicate values, but each combination of values from all the indexed fields must be unique. A primary index consists of a key for the table and usually contains the same fields as the primary key.

The Primary property setting is read/write for a new CdbIndex object not yet appended to a collection and read-only for an existing CdbIndex object in an Indexes collection. If the CdbIndex object is appended to the CdbTableDef object but the CdbTableDef object isn't appended to the TableDefs collection, the Primary property is read/write.

Note You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record can take a long time. The Attributes property of each CdbField object in the CdbIndex object determines the order of records and consequently determines the access techniques to use for that index. When you create a new table in your database, it's a good idea to create an index on one or more fields that uniquely identify each record, and then set the Primary property of the CdbIndex object to True.

When you set a primary key for a table, the primary key is automatically defined as the primary index for the table.


QueryTimeout Property (DAO)

QueryTimeout Property

Sets or returns a value that specifies the number of seconds to wait before a timeout error occurs when a query is executed on an ODBC data source.

Syntax

VOIDSetQueryTimeout(SHORT sTime);

SHORTGetQueryTimeout(VOID);

Parameters

Type | Argument | Description
SHORT | sTime | An integer specifying the number of seconds before DAO times out. The default value is 60.

Remarks

When you're using an ODBC database, such as Microsoft SQL Server, there may be delays due to network traffic or heavy use of the ODBC server. Rather than waiting indefinitely, you can specify how long to wait.

When you use QueryTimeout with a CdbConnection or CdbDatabase object, it specifies a global value for all queries associated with the database. You can override this value for a specific query by setting the ODBCTimeout property of the particular CdbQueryDef object.

In a Microsoft Jet workspace, you can override the default value by creating a new “ODBC” key in the Registry path \HKEY_LOCAL_MACHINE\SOFTWARE\Jet\3.5\, creating a QueryTimeout parameter in this key, and setting the value as desired.


RecordCount Property (DAO)

RecordCount Property

Returns the number of records accessed in a CdbRecordset object or the total number of records in a table-type CdbRecordset or CdbTableDef object.

Syntax

LONGGetRecordCount(VOID);

Remarks

Use the RecordCount property to find out how many records in a CdbRecordset or CdbTableDef object have been accessed. The RecordCount property doesn't indicate how many records are contained in a dynaset-, snapshot-, or forward-only–type CdbRecordset object until all records have been accessed. Once the last record has been accessed, the RecordCount property indicates the total number of undeleted records in the CdbRecordset or CdbTableDef object. To force the last record to be accessed, use the MoveLast method on the CdbRecordset object. You can also use an SQL Count function to determine the approximate number of records your query will return.

Note Using the MoveLast method to populate a newly opened CdbRecordset negatively impacts performance. Unless it is necessary to have an accurate RecordCount as soon as you open a CdbRecordset, it's better to wait until you populate the CdbRecordset with other portions of code before checking the RecordCount property.

As your application deletes records in a dynaset-type CdbRecordset object, the value of the RecordCount property decreases. However, records deleted by other users aren't reflected by the RecordCount property until the current record is positioned to a deleted record. If you execute a transaction that affects the RecordCount property setting and you subsequently roll back the transaction, the RecordCount property won't reflect the actual number of remaining records.

The RecordCount property of a snapshot- or forward-only–type CdbRecordset object isn't affected by changes in the underlying tables.

A CdbRecordset or CdbTableDef object with no records has a RecordCount property setting of 0.

When you work with linked CdbTableDef objects, the RecordCount property setting is always –1.

Using the Requery method on a CdbRecordset object resets the RecordCount property just as if the query were re-executed.


RecordsAffected Property (DAO)

RecordsAffected Property

Returns the number of records affected by the most recently invoked Execute method.

Syntax

LONGGetRecordsAffected(VOID);

Remarks

When you use the Execute method to run an action query from a CdbQueryDef object, the RecordsAffected property will contain the number of records deleted, updated, or inserted.

When you use RecordsAffected in an ODBCDirect workspace, it will not return a useful value from an SQL DROP TABLE action query.


RecordStatus Property (DAO)

RecordStatus Property

Returns a value indicating the update status of the current record if it is part of a batch update (ODBCDirect workspaces only).

Syntax

SHORTGetRecordStatus(VOID);

VOIDSetRecordStatus(SHORT iStatus);

Parameters

Type | Argument | Description
SHORT | iStatus | A Short with one or more of the values specified in Remarks.

Remarks

The value of the RecordStatus property indicates whether and how the current record will be involved in the next optimistic batch update, using the following constants:

Constant | Description
dbRecordUnmodified | (Default) The record has not been modified or has been updated successfully.
dbRecordModified | The record has been modified and not updated in the database.
dbRecordNew | The record has been inserted with the AddNew method, but not yet inserted into the database.
dbRecordDeleted | The record has been deleted, but not yet deleted in the database.
dbRecordDBDeleted | The record has been deleted locally and in the database.

When a user changes a record, the RecordStatus for that record automatically changes to dbRecordModified. Similarly, if a record is added or deleted, RecordStatus reflects the appropriate constant. When you then use a batch-mode Update method, DAO will submit an appropriate operation to the remote server for each record, based on the record's RecordStatus property.


Replicable Property (DAO)

Replicable Property

Sets or returns a value that determines whether a database or object in a database can be replicated (Microsoft Jet workspaces only).

Note Before getting or setting the Replicable property on a CdbDatabase, CdbTableDef, or CdbQueryDef object, you must create it by using the CreateProperty method and append it to the Properties collection for the object.

Syntax

There is no member function to explicitly access this property. See Usage below for an example of how this property is managed.

Remarks

On a CdbDatabase object, setting this property to "T" makes the database replicable. Once you set the property to "T", you can't change it; setting the property to "F" (or any value other than "T") causes an error.

On an object in a database, setting this property to "T" replicates the object (and subsequent changes to the object) at all replicas in the replica set. You can also set this property in the object's property sheet in Microsoft Access.

Note Microsoft Jet 3.5 also supports the Boolean ReplicableBool property. Its functionality is identical to the Replicable property, except that it takes a Boolean value. Setting ReplicableBool to True makes the object replicable.

Before setting the Replicable property on a database, make a backup copy of the database. If setting the Replicable property fails, you should delete the partially replicated database, make a new copy from the backup, and try again.

When you set this property on a CdbDatabase object, Microsoft Jet adds fields, tables, and properties to objects within the database. Microsoft Jet uses these fields, tables, and properties to synchronize database objects. For example, all existing tables have three new fields added to them that help identify which records have changed. The addition of these fields and other objects increases the size of your database.

On forms, reports, macros, and modules defined by a host application (such as Microsoft Access), you set this property on the host-defined object through the host user interface. Once set, the Replicable property will appear in the Properties collection for the CdbDocument object representing the host object.

If the Replicable property has already been set on an object using the Replicated check box in the property sheet for the object, you cannot set the Replicable property in code.

When you create a new table, query, form, report, macro, or module at a replica, the object is considered local and is stored only at that replica. If you want users at other replicas to be able to use the object, you must change it from local to replicable. Either create the object at or import it into the Design Master and then set the Replicable property to "T".

The object on which you are setting the Replicable property might have already inherited that property from another object. However, the value set by the other object has no effect on the behavior of the object you want to make replicable. You must explicitly set the property for each object.

Usage

...
CdbDBEngine      engine;
CdbProperty      prp;
CdbQueryDef      qdf;
COleVariant      vTrue(_T("T"));
...
// Initialize engine, queryDef, etc.
prp = qdf.CreateProperty(
            _T("Replicable"), dbText, &vTrue);
qdf.Properties.Append( prp );
...
prp = qdf.Properties[_T("Replicable")];
if (prp.GetValue() == vTrue)
   {
   prp = qdf.CreateProperty(
            _T("KeepLocal"), dbText, &vTrue);
   qdf.Properties.Append( prp );
   }
...


ReplicaFilter Property (DAO)

ReplicaFilter Property

Sets or returns a value on a CdbTableDef object within a partial replica that indicates which subset of records is replicated to that table from a full replica. (Microsoft Jet databases only.)

Syntax

VOIDSetReplicaFilter(LPVARIANT pv );

COleVariantGetReplicaFilter(VOID);

Parameters

Type | Argument | Description
LPVARIANT | pv | A pointer to a variant whose value is a string or Boolean that indicates which subset of records is replicated as described in Remarks.

Remarks

This property indicates which subset of records is replicated, as specified in the following table:

Value | Description
A string | A criteria that a record in the partial replica table must satisfy in order to be replicated from the full replica.
True | Replicates all records.
False | (Default) Doesn't replicate any records.

If you use a string, it is similar to an SQL WHERE clause (without the word WHERE), but you cannot specify subqueries, aggregate functions (such as Count), or user-defined functions within the criteria.

You can only synchronize data between a full replica and a partial replica. You can't synchronize data between two partial replicas. Also, with partial replication you can set restrictions on which records are replicated, but you can't indicate which fields are replicated.

Usually, you reset a replica filter when you want to replicate a different set of records. For example, when a sales representative temporarily takes over another sales representative's region, the database application can temporarily replicate data for both regions and then return to the previous filter. In this scenario, the application resets the ReplicaFilter property and then repopulates the partial replica.

If your application changes replica filters, you should follow these steps:

  1. Use the Synchronize method to synchronize your full replica with the partial replica in which the filters are being changed.

  2. Use the ReplicaFilter property to make the desired changes to the replica filter.

  3. Use the PopulatePartial method to remove all records from the partial replica and transfer all records from the full replica that meet the new replica filter criteria.

To remove a filter, set the ReplicaFilter property to False. If you remove all filters and invoke the PopulatePartial method, no records will appear in any replicated tables in the partial replica.

Note If a replica filter has changed, and the Synchronize method is invoked without first invoking PopulatePartial, a trappable error occurs.


ReplicaID Property (DAO)

ReplicaID Property

Returns a 16-byte GUID that uniquely identifies a database design master or replica (Microsoft Jet workspaces only).

Syntax

CStringGetReplicaID(VOID);

Remarks

The Microsoft Jet database engine automatically generates this value when you create a new replica.

The ReplicaID property of each replica (and the Design Master) is stored in the MSysReplicas system table.


Required Property (DAO)

Required Property

Sets or returns a value that indicates whether a CdbField object requires a non-Null value or whether all the fields in a CdbIndex object must have a value.

Syntax

VOIDSetRequired(BOOL bFlag );

BOOLGetRequired(VOID);

Parameters

Type | Argument | Description
BOOL | bFlag | TRUE if a field can't contain a Null value.

Remarks

The availability of the Required property depends on the object that contains the Fields collection, as shown in the following table.

If the Fields collection belongs to a | Then Required is
CdbIndex object | Not supported
CdbQueryDef object | Read-only
CdbRecordset object | Read-only
CdbRelation object | Not supported
CdbTableDef object | Read/write

For an object not yet appended to a collection, this property is read/write. For a CdbIndex object, this property setting is read-only for appended objects.

For a Field object, you can use the Required property along with the AllowZeroLength, ValidateOnSet, or ValidationRule property to determine the validity of the Value property setting for that CdbField object. If the Required property is set to False, the field can contain Null values as well as values that meet the conditions specified by the AllowZeroLength and ValidationRule property settings.

Note When you can set this property for either a CdbIndex object or a CdbField object, set it for the CdbField object. The validity of the property setting for a CdbField object is checked before that of a CdbIndex object.


Restartable Property (DAO)

Restartable Property

Returns a value that indicates whether a CdbRecordset object supports the Requery method, which re-executes the query on which the CdbRecordset object is based.

Syntax

BOOLGetRestartable(VOID);

Remarks

Verify that the Restartable property is True before using the Requery method on a CdbRecordset object. If the object's Restartable property is set to False, use the OpenRecordset method on the underlying CdbQueryDef object to re-execute the query.


ReturnsRecords Property (DAO)

ReturnsRecords Property

Sets or returns a value that indicates whether an SQL pass-through query to an external database returns records.

Syntax

VOIDSetReturnsRecords(BOOL bFlag );

BOOLGetReturnsRecords(VOID);

Parameters

Type | Argument | Description
BOOL | bFlag | TRUE if a pass-through query returns records.

Remarks

Not all SQL pass-through queries to external databases return records. For example, an SQL UPDATE statement updates records without returning records, while an SQL SELECT statement does return records. If the query returns records, set the ReturnsRecords property to True; if the query doesn't return records, set the ReturnsRecords property to False.

Note You must set the Connect property before you set the ReturnsRecords property.


Size Property (DAO)

Size Property

Sets or returns a value that indicates the maximum size, in bytes, of a CdbField object.

Syntax

VOIDSetSize(LONG lSize );

LONGGetSize(VOID);

Parameters

Type | Argument | Description
LONG | lSize | A Long that specifies the length of the field.

Remarks

For an object not yet appended to the Fields collection, this property is read/write.

For fields (other than Memo type fields) that contain character data, the Size property indicates the maximum number of characters that the field can hold. For numeric fields, the Size property indicates how many bytes of storage are required.

Use of the Size property depends on the object that contains the Fields collection to which the CdbField object is appended, as shown in the following table.

Object appended to | Usage
CdbIndex | Not supported
CdbQueryDef | Read-only
CdbRecordset | Read-only
CdbRelation | Not supported
CdbTableDef | Read-only

When you create a CdbField object with a data type other than Text, the Type property setting automatically determines the Size property setting; you don't need to set it. For a CdbField object with the Text data type, however, you can set Size to any integer up to the maximum text size (255 for Microsoft Jet databases). If you do not set the size, the field will be as large as the database allows.

For Long Binary and Memo CdbField objects, Size is always set to 0. Use the FieldSize method of the CdbField object to determine the size of the data in a specific record. The maximum size of a Long Binary or Memo field is limited only by your system resources or the maximum size that the database allows.


Sort Property (DAO)

Sort Property

Sets or returns the sort order for records in a CdbRecordset object (Microsoft Jet workspaces only).

Syntax

VOIDSetSort(LPCTSTR pstr );

CStringGetSort(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstr | A pointer to a string that contains the ORDER BY clause of an SQL statement without the reserved words ORDER BY.

Remarks

You can use the Sort property with dynaset- and snapshot-type CdbRecordset objects.

When you set this property for an object, sorting occurs when a subsequent CdbRecordset object is created from that object. The Sort property setting overrides any sort order specified for a CdbQueryDef object.

The default sort order is ascending (A to Z or 0 to 100).

The Sort property doesn't apply to table- or forward-only–type CdbRecordset objects. To sort a table-type CdbRecordset object, use the CdbIndex property.

Note In many cases, it's faster to open a new CdbRecordset object by using an SQL statement that includes the sorting criteria.


Source Property (DAO)

Source Property

Returns the name of the object or application that originally generated the error.

Syntax

CStringGetSource(VOID);

Remarks

The Source property value is usually the object's class name or programmatic ID. Use the Source property to provide your users with information when your code is unable to handle an error generated in an object in another application.

Based on all of the error documentation, you can write code that will handle the error appropriately. If your error handler fails, you can use the CdbError object information to describe the error to your user, using the Source property and the other CdbError properties to give the user information about which object originally caused the error, the description of the error, and so forth.

For example, if you access Microsoft Excel and it generates a "Division by zero" error, Microsoft Excel sets CdbError.Number to the Microsoft Excel code for that error and sets the Source property to Excel.Application. Note that if the error is generated in another object called by Microsoft Excel, Microsoft Excel intercepts the error and still sets CdbError.Number to the Microsoft Excel code. However, the other CdbError object properties (including Source) will retain the values as set by the object that generated the error. The Source property always contains the name of the object that originally generated the error.


SourceField, SourceTable Properties (DAO)

SourceField, SourceTable Properties

  • SourceField returns the name of the field that is the original source of the data for a CdbField object.

  • SourceTable returns the name of the table that is the original source of the data for a CdbField object.

Syntax: GetSourceField

CStringGetSourceField(VOID);

Syntax: GetSourceTable

CStringGetSourceTable(VOID);

Remarks

For a CdbField object, use of the SourceField and SourceTable properties depends on the object that contains the Fields collection that the CdbField object is appended to, as shown in the following table.

Object appended to | Usage
CdbIndex | Not supported
CdbQueryDef | Read-only
CdbRecordset | Read-only
CdbRelation | Not supported
CdbTableDef | Read-only

These properties indicate the original field and table names associated with a CdbField object. For example, you could use these properties to determine the original source of the data in a query field whose name is unrelated to the name of the field in the underlying table.

Note The SourceTable property will not return a meaningful table name if used on a CdbField object in the Fields collection of a table-type CdbRecordset object.


SourceTableName Property (DAO)

SourceTableName Property

Sets or returns a value that specifies the name of a linked table or the name of a base table (Microsoft Jet workspaces only).

Syntax

VOIDSetSourceTableName(LPCTSTR pstr );

CStringGetSourceTableName(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstr | A pointer to a string that specifies a table name.

Remarks

For a base table, the setting is a zero-length string (""). This property setting is read-only for a base table and read/write for a linked table or an object not appended to a collection.


SQL Property (DAO)

SQL Property

Sets or returns the SQL statement that defines the query executed by a CdbQueryDef object.

Syntax

VOIDSetSQL(LPCTSTR pstr );

CStringGetSQL(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstr | A pointer to a string that contains an SQL statement.

Remarks

The SQL property contains the SQL statement that determines how records are selected, grouped, and ordered when you execute the query. You can use the query to select records to include in a CdbRecordset object. You can also define action queries to modify data without returning records.

The SQL syntax used in a query must conform to the SQL dialect of the query engine, which is determined by the type of workspace. In a Microsoft Jet workspace, use the Microsoft Jet SQL dialect, unless you create an SQL pass-through query, in which case you should use the dialect of the server. In an ODBCDirect workspace, use the SQL dialect of the server.

Note You can send DAO queries to a variety of different database servers with ODBCDirect, and different servers will recognize slightly different dialects of SQL. Therefore, context-sensitive Help is no longer provided for Microsoft Jet SQL, although online Help for Microsoft Jet SQL is still included through the Help menu. Be sure to check the appropriate reference documentation for the SQL dialect of your database server when using either ODBCDirect connections or pass-through queries in Microsoft Jet-connected client/server applications.

If the SQL statement includes parameters for the query, you must set these before execution. Until you reset the parameters, the same parameter values are applied each time you execute the query.

In an ODBCDirect workspace, you can also use the SQL property to execute a prepared statement on the server. For example, setting the SQL property to the following string will execute a prepared statement named “GetData” with one parameter on a Microsoft SQL Server back-end.

"{call GetData (?)}"

In a Microsoft Jet workspace, using a CdbQueryDef object is the preferred way to perform SQL pass-through operations on Microsoft Jet-connected ODBC data sources. By setting the CdbQueryDef object's Connect property to an ODBC data source, you can use non–Microsoft-Jet-database SQL in the query to be passed to the external server. For example, you can use TRANSACT SQL statements (with Microsoft SQL Server or Sybase SQL Server databases), which the Microsoft Jet database engine would otherwise not process.

Note If you set the property to a string concatenated with a non-integer value, and the system parameters specify a non-U.S. decimal character such as a comma (for example, strSQL = "PRICE > " & lngPrice, and lngPrice = 125,50), an error will result when you try to execute the CdbQueryDef object in a Microsoft Jet database. This is because during concatenation, the number will be converted to a string using your system's default decimal character and Microsoft Jet SQL only accepts U.S. decimal characters.


StillExecuting Property (DAO)

StillExecuting Property

Indicates whether or not an asynchronous operation (that is, a method called with the dbRunAsync option) has finished executing (ODBCDirect workspaces only).

Syntax

BOOLGetStillExecuting(VOID);

Remarks

Use the StillExecuting property to determine if the most recently called asynchronous Execute, MoveLast, OpenConnection, or OpenRecordset method (that is, a method executed with the dbRunAsync option) is complete. The return value is True if the query is still executing and False if the query has completed. While the StillExecuting property is True, any returned object cannot be accessed.

The following table shows what method is evaluated when you use StillExecuting on a particular type of object.

If StillExecuting is used on | This asynchronous method is evaluated
CdbConnection | Execute or OpenConnection
CdbQueryDef | Execute
CdbRecordset | MoveLast or OpenRecordset

Once the StillExecuting property on a CdbConnection or CdbRecordset object returns False, follwing the OpenConnection or OpenRecordset call that returns the associated CdbRecordset or CdbConnection object, the object can be referenced. So long as StillExecuting remains True, the object may not be referenced, other than to read the StillExecuting property. When you use the NextRecordset method to complete processing of a CdbRecordset, the StillExecuting property is reset to True while subsequent result sets are retrieved.

Use the Cancel method to terminate execution of a task in progress.


SystemDB Property (DAO)

SystemDB Property

Sets or returns the path for the current location of the workgroup information file (Microsoft Jet workspaces only).

Syntax

VOIDSetSystemDB(LPCTSTR pstr );

CStringGetSystemDB(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstr | A pointer to a string containing the path to the system database file.

Remarks

The Microsoft Jet database engine allows you to define a workgroup and set different access permissions to each object in the database for each user in the workgroup. The workgroup is defined by the workgroup information file, typically called "system.mda". For users to gain access to the secured objects in your database, DAO must have the location of this workgroup information file. The location can be identified to DAO either by specifying it in the Windows Registry or by setting the SystemDB property. On setup, the default setting is simply "system.mda" with no path.

For this option to have any effect, you must set the SystemDB property before your application initializes the CdbDBEngine object (that is, before creating an instance of any other DAO object). The scope of this setting is limited to your application and can't be changed without restarting your application.


Table Property (DAO)

Table Property

Indicates the name of a CdbRelation object's primary table. This should be equal to the Name property setting of a CdbTableDef or CdbQueryDef object (Microsoft Jet workspaces only).

Syntax

VOIDSetTable(LPCTSTR pstr );

CStringGetTable(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstr | A pointer to a string that contains the name of a table in the TableDefs collection or query in the QueryDefs collection.

Remarks

The Table property setting is read/write for a new CdbRelation object not yet appended to a collection and read-only for an existing CdbRelation object in a Relations collection.

Use the Table property with the ForeignTable property to define a CdbRelation object, which represents the relationship between fields in two tables or queries. Set the Table property to the Name property setting of the primary CdbTableDef or CdbQueryDef object, and set the ForeignTable property to the Name property setting of the foreign (referencing) CdbTableDef or CdbQueryDef object. The Attributes property determines the type of relationship between the two objects.

For example, if you had a list of valid part codes (in a field named PartNo) stored in a ValidParts table, you could establish a one-to-many relationship with an OrderItem table such that if a part code were entered into the OrderItem table, it would have to already be in the ValidParts table. If the part code didn't exist in the ValidParts table and you had not set the Attributes property of the CdbRelation object to dbRelationDontEnforce, a trappable error would occur.

In this case, the ValidParts table is the primary table, so the Table property of the CdbRelation object would be set to ValidParts and the ForeignTable property of the CdbRelation object would be set to OrderItem. The Name and ForeignName properties of the CdbField object in the CdbRelation object's Fields collection would be set to PartNo.

The following illustration depicts this relation.


Transactions Property (DAO)

Transactions Property

Returns a value that indicates whether an object supports transactions.

Syntax

BOOLGetTransactions(VOID);

Remarks

In an ODBCDirect workspace, the Transactions property is available on Connection and Database objects and indicates whether or not the ODBC driver you are using supports transactions.

In a Microsoft Jet workspace, you can also use the Transactions property with dynaset- or table-type CdbRecordset objects. Snapshot- and forward-only–type CdbRecordset objects always return False.

If a dynaset- or table-type CdbRecordset is based on a Microsoft Jet database engine table, the Transactions property is True and you can use transactions. Other database engines may not support transactions. For example, you can't use transactions in a dynaset-type CdbRecordset object based on a Paradox table.

Check the Transactions property before using the BeginTrans method on the CdbRecordset object's CdbWorkspace object to make sure that transactions are supported. Using the BeginTrans, CommitTrans, or Rollback methods on an unsupported object has no effect.


Type Property (DAO)

Type Property

Sets or returns a value that indicates the operational type or data type of an object.

Syntax

VOIDSetType(SHORT sType );

SHORTGetType(VOID);

Remarks

For a CdbField or CdbProperty object, this property is read/write until the object is appended to a collection or to another object, after which it's read-only. For a CdbParameter object in a Microsoft Jet workspace the property is read-only, while in an ODBCDirect workspace the property is always read-write. For any of these objects, the possible settings and return values are described in the following table.

Constant | Description
dbBigInt | Big Integer
dbBinary | Binary
dbBoolean | Boolean
dbByte | Byte
dbChar | Char
dbCurrency | Currency
dbDate | Date/Time
dbDecimal | Decimal
dbDouble | Double
dbFloat | Float
dbGUID | GUID
dbInteger | Integer
dbLong | Long
dbLongBinary | Long Binary (OLE Object)
dbMemo | Memo
dbNumeric | Numeric
dbSingle | Single
dbText | Text
dbTime | Time
dbTimeStamp | Time Stamp
dbVarBinary | VarBinary

For a CdbQueryDef object, the property is read-only. The possible return values are shown in the following table.

Constant | CdbQueryDef type
dbQAction | Action
dbQAppend | Append
dbQCompound | Compound
dbQCrosstab | Crosstab
dbQDDL | Data-definition
dbQDelete | Delete
dbQMakeTable | Make-table
dbQProcedure | Procedure (ODBCDirect workspaces only)
dbQSelect | Select
dbQSetOperation | Union
dbQSPTBulk | Used with dbQSQLPassThrough to specify a query that doesn't return records (Microsoft Jet workspaces only).
dbQSQLPassThrough | Pass-through (Microsoft Jet workspaces only)
dbQUpdate | Update

Note To create an SQL pass-through query in a Microsoft Jet workspace, you don't need to explicitly set the Type property to dbQSQLPassThrough. The Microsoft Jet database engine automatically sets this when you create a CdbQueryDef object and set the Connect property.

For a CdbRecordset,object, the property is read-only, and the possible return values are as follows.

Constant | CdbRecordset type
dbOpenTable | Table (Microsoft Jet workspaces only)
dbOpenDynamic | Dynamic (ODBCDirect workspaces only)
dbOpenDynaset | Dynaset
dbOpenSnapshot | Snapshot
dbOpenForwardOnly | Forward-only

For a CdbWorkspace object, the property is read-only, and the possible settings are as follows.

Constant | CdbWorkspace type
dbUseJet | The CdbWorkspace is connected to the Microsoft Jet database engine.
dbUseODBC | The CdbWorkspace is connected to an ODBC data source.

When you append a new CdbField, CdbParameter, or CdbProperty object to the collection of an CdbIndex, CdbQueryDef, CdbRecordset, or CdbTableDef object, an error occurs if the underlying database doesn't support the data type specified for the new object.


Unique Property (DAO)

Unique Property

Sets or returns a value that indicates whether an CdbIndex object represents a unique (key) index for a table (Microsoft Jet workspaces only).

Syntax

VOIDSetUnique(BOOL bFlag );

BOOLGetUnique(VOID);

Parameters

Type | Argument | Description
BOOL | bFlag | TRUE if the CdbIndex object represents a unique index.

Remarks

For a CdbIndex object, this property setting is read/write until the object is appended to a collection, after which it's read-only.

A unique index consists of one or more fields that logically arrange all records in a table in a unique, predefined order. If the index consists of one field, values in that field must be unique for the entire table. If the index consists of more than one field, each field can contain duplicate values, but each combination of values from all the indexed fields must be unique.

If both the Unique and Primary properties of a CdbIndex object are set to True, the index is unique and primary: It uniquely identifies all records in the table in a predefined, logical order. If the Primary property is set to False, the index is a secondary index. Secondary indexes (both key and nonkey) logically arrange records in a predefined order without serving as an identifier for records in the table.

Notes

  • You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record can take a long time.

  • Records retrieved from tables without indexes are returned in no particular sequence.

  • The Attributes property of each CdbField object in the CdbIndex object determines the order of records and consequently determines the access techniques to use for that CdbIndex object.

  • A unique index helps optimize finding records.

  • Indexes don't affect the physical order of a base table — indexes affect only how the records are accessed by the table-type CdbRecordset object when a particular index is chosen or when the Microsoft Jet database engine creates Recordset objects.


Updatable Property (DAO)

Updatable Property

Returns a value that indicates whether you can change a DAO object.

Syntax

BOOLGetUpdatable(VOID);

Remarks

Depending on the object, if the Updatable property setting is True, the associated statement in the following table is true.

Object | Updatable indicates
CdbDatabase | Object can be changed.
CdbQueryDef | Query definition can be changed.
CdbRecordset | Records can be updated.
CdbTableDef | Table definition can be changed.

The Updatable property setting is always True for a newly created CdbTableDef object and False for a linked CdbTableDef object. A new CdbTableDef object can be appended only to a database for which the current user has write permission.

Many types of objects can contain fields that can't be updated. For example, you can create a dynaset-type CdbRecordset object in which only some fields can be changed. These fields can be fixed or contain data that increments automatically or the dynaset can result from a query that combines updatable and nonupdatable tables.

If the object contains only read-only fields, the value of the Updatable property is False. When one or more fields are updatable, the property's value is True. You can edit only the updatable fields. A trappable error occurs if you try to assign a new value to a read-only field.

The Updatable property of a CdbQueryDef object is set to True if the query definition can be updated, even if the resulting CdbRecordset object isn't updatable.

Because an updatable object can contain read-only fields, check the DataUpdatable property of each field in the Fields collection of a CdbRecordset object before you edit a record.

Snapshot- and forward-only–type CdbRecordset objects always return False.


UpdateOptions Property (DAO)

UpdateOptions Property

Sets or returns a value that indicates how the WHERE clause is constructed for each record during a batch update, and whether the batch update should use an UPDATE statement or a DELETE followed by an INSERT (ODBCDirect workspaces only).

Syntax

VOIDSetUpdateOptions(LONG lOptions );

LONGGetUpdateOptions(VOID);

Parameters

Type | Argument | Description
LONG | lOptions | A Long with one or more of the values specified in Remarks.

Remarks

The setting or return value can be any of the following constants:

Constant | Uses
dbCriteriaKey | (Default) Jjust the key column(s) in the where clause.
dbCriteriaModValues | Key column(s) and all updated columns in the where clause.
dbCriteriaAllCols | Key column(s) and all the columns in the where clause.
dbCriteriaTimeStamp | Just the timestamp column if available (will generate a run-time error if no timestamp column is in the result set).
dbCriteriaDeleteInsert | Set of DELETE and INSERT statements for each modified row.
dbCriteriaUpdate | (Default) UPDATE statement for each modified row.

When a batch-mode Update is executed, DAO and the client batch cursor library create a series of SQL UPDATE statements to make the needed changes. An SQL WHERE clause is created for each update to isolate the records that are marked as changed by the RecordStatus property. Because some remote servers use triggers or other ways to enforce referential integrity, is it often important to limit the fields being updated to just those affected by the change. To do this, set the UpdateOptions property to one of the constants dbCriteriaKey, dbCriteriaModValues, dbCriteriaAllCols, or dbCriteriaTimeStamp. This way, only the absolute minimum amount of trigger code is executed. As a result, the update operation is executed more quickly, and with fewer potential errors.

You can also concatenate either of the constants dbCriteriaDeleteInsert or dbCriteriaUpdate to determine whether to use a set of SQL DELETE and INSERT statements or an SQL UPDATE statement for each update when sending batched modifications back to the server. In the former case, two separate operations are required to update the record. In some cases, especially where the remote system implements DELETE, INSERT, and UPDATE triggers, choosing the correct UpdateOptions property setting can significantly impact performance.

If you don't specify any constants, dbCriteriaUpdate and dbCriteriaKey will be used.

Newly added records will always generate INSERT statements and deleted records will always generate DELETE statements, so this property only applies to how the cursor library updates modified records.


UserName Property (DAO)

UserName Property

Sets or returns a value that represents a user, a group of users, or the owner of a CdbWorkspace object.

Syntax

VOIDSetUserName(LPCTSTR pstrName );

CStringGetUserName(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstrName | A pointer to a string that contains the name of a user.

Remarks

In a Microsoft Jet workspace, this property represents a CdbUser object in the Users collection or a CdbGroup object in the Groups collection. For Microsoft Jet CdbContainer and CdbDocument objects, this property setting is read/write. For all CdbWorkspace objects, this property setting is read-only.

Depending on the type of object, the UserName property represents the following:

  • The owner of a CdbWorkspace object.

  • A user or group of users when you manipulate the access permissions of a CdbContainer object or a CdbDocument object (Microsoft Jet workspaces only).

To find or set the permissions for a particular user or group of users, first set the UserName property to the user or group name that you want to examine. Then check the Permissions property setting to determine what permissions that user or group of users has, or set the Permissions property to change the permissions.

For a CdbWorkspace object, check the UserName property setting to determine the owner of the CdbWorkspace object. Set the UserName property to establish the owner of the CdbWorkspace object before you append the object to the Workspaces collection.


V1xNullBehavior Property (DAO)

V1xNullBehavior Property

Indicates whether zero-length strings ("") used in code to fill Text or Memo fields are converted to Null. The setting or return value is a Boolean that is True if zero-length strings are converted to Null.

Syntax

There is no member function to explicitly access this property. See Usage below for an example of how this property is managed.

Remarks

This property applies to Microsoft Jet database engine version 1.x databases that have been converted to Microsoft Jet database engine version 2.0 or 3.x databases.

Note The Microsoft Jet database engine automatically creates this property when it converts a version 1.x database to a version 2.0 or 3.x database. A 2.0 database will retain this property when it is converted to a 3.x database.

If you change this property setting, you must close and then reopen the database for your change to take effect.

For fastest performance, modify code that sets any Text or Memo fields to zero-length strings so that the fields are set to Null instead, and remove the V1xNullBehavior property from the Properties collection.

Usage

/* Assume that you want to change the way nulls are handled in a converted database.
Notes:
   1) We'll break getting the property and the value into two steps for readability.
   2) The COleVariant "==" operator requires two variants.
*/
CdbDBEngine   dbeng;
CdbDatabase   dbs;
CdbProperty   prp;
COleVariant   vTrue((short)TRUE, VT_BOOL),
         vFalse((short)FALSE, VT_BOOL),
         vVal;
//
dbs = dbeng.OpenDatabase(_T("AConvertedV1.mdb"));
prp = dbs.Properties[_T("V1xNullBehavior")];
vVal = prp.GetValue();      // note 1
if (vVal == vTrue)          // note 2
   {
   prp.SetValue(&vFalse);
   dbs.Close();
   dbs = dbeng.OpenDatabase(_T("AConvertedV1.mdb"));
   }
...


ValidateOnSet Property (DAO)

ValidateOnSet Property

Sets or returns a value that specifies whether or not the value of a CdbField object is immediately validated when the object's Value property is set (Microsoft Jet workspaces only).

Syntax

VOIDSetValidateOnSet(BOOL bFlag );

BOOLGetValidateOnSet(VOID);

Parameters

Type | Argument | Description
BOOL | bFlag | A Boolean. TRUEthe validation rule is checked when you set the object's Value property. FALSEthe validation rule is checked when the record is updated.

Remarks

Only CdbField objects support the ValidateOnSet property as read/write.

Setting the ValidateOnSet property to True can be useful in a situation when a user is entering records that include substantial Memo data. Waiting until the Update call to validate the data can result in unnecessary time spent writing the lengthy Memo data to the database if it turns out that the data was invalid anyway because a validation rule was broken in another field.


ValidationRule Property (DAO)

ValidationRule Property

Sets or returns a value that validates the data in a field as it's changed or added to a table (Microsoft Jet workspaces only).

Syntax

VOIDSetValidationRule(LPCTSTR pstr );

CStringGetValidationRule(VOID);

Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to string that contains a comparison in the form of an SQL WHERE clause without the WHERE reserved word.

Remarks

For an object not yet appended to the Fields collection, this property is read/write.

The ValidationRule property determines whether or not a field contains valid data. If the data is not valid, a trappable run-time error occurs. The returned error message is the text of the ValidationText property, if specified, or the text of the expression specified by ValidationRule.

For a CdbField object, use of the ValidationRule property depends on the object that contains the Fields collection to which the CdbField object is appended.

Object appended to | Usage
CdbIndex | Not supported
CdbQueryDef | Read-only
CdbRecordset | Read-only
CdbRelation | Not supported
CdbTableDef | Read/write

For a CdbRecordset object, use of the ValidationRule property is read-only. For a CdbTableDef object, use of the ValidationRule property depends on the status of the CdbTableDef object, as the following table shows.

TableDef | Usage
Base table | Read/write
Linked table | Read-only

Validation is supported only for databases that use the Microsoft Jet database engine.

The string expression specified by the ValidationRule property of a CdbField object can refer only to that CdbField. The expression can't refer to user-defined functions, SQL aggregate functions, or queries. To set a CdbField object's ValidationRule property when its ValidateOnSet property setting is True, the expression must successfully parse (with the field name as an implied operand) and evaluate to True. If its ValidateOnSet property setting is False, the ValidationRule property setting is ignored.

The ValidationRule property of a Recordset or TableDef object can refer to multiple fields in that object. The restrictions noted earlier in this topic for the CdbField object apply.

For a table-type CdbRecordset object, the ValidationRule property inherits the ValidationRule property setting of the CdbTableDef object that you use to create the table-type CdbRecordset object.

For a CdbTableDef object based on an linked table, the ValidationRule property inherits the ValidationRule property setting of the underlying base table. If the underlying base table doesn't support validation, the value of this property is a zero-length string ("").

Note If you set the property to a string concatenated with a non-integer value, and the system parameters specify a non-U.S. decimal character such as a comma (for example, strRule = "PRICE > " & lngPrice, and lngPrice = 125,50), an error will result when your code attempts to validate any data. This is because during concatenation, the number will be converted to a string using your system's default decimal character, and Microsoft Jet SQL only accepts U.S. decimal characters.


ValidationText Property (DAO)

ValidationText Property

Sets or returns a value that specifies the text of the message that your application displays if the value of a CdbField object doesn't satisfy the validation rule specified by the ValidationRule property setting (Microsoft Jet workspaces only).

Syntax

VOIDSetValidationText(LPCTSTR pstr );

CStringGetValidationText(VOID);

Parameters

Type | Argument | Description
LPCTSTR | pstr | A pointer to a string that contains the text message.

Remarks

For an object not yet appended to a collection, this property is read/write. For a CdbRecordset object, this property setting is read-only. For a CdbTableDef object, this property setting is read-only for a linked table and read/write for a base table.

For a CdbField object, use of the ValidationText property depends on the object that contains the Fields collection to which the CdbField object is appended, as the following table shows.

Object appended to | Usage
CdbIndex | Not supported
CdbQueryDef | Read-only
CdbRecordset | Read-only
CdbRelation | Not supported
CdbTableDef | Read/write


Value Property (DAO)

Value Property

Sets or returns the value of an object.

Syntax

VOIDSetValue(LPVARIANT pv );

COleVariantGetValue(VOID);

Parameters

Type | Argument | Description
LPVARIANT | pv | A pointer to a COleVariant that contains the value to be inserted into the CdbField object.

Remarks

Generally, the Value property is used to retrieve and alter data in CdbRecordset objects.

The Value property is the default property of the CdbField, CdbParameter, and CdbProperty objects. Therefore, you can set or return the value of one of these objects by referring to them directly instead of specifying the Value property.

Trying to set or return the Value property in an inappropriate context (for example, the Value property of a CdbField object in the Fields collection of a CdbTableDef object) will cause a trappable error.

Notes

  • In an ODBCDirect workspace, you cannot read or set the Value property of a CdbRecordset field more than once without refreshing the current record. For example, to read and then set the Value property, first read the property, then use the Move 0 method to refresh the current record, then write the new value.

  • When reading decimal values from a Microsoft SQL Server database, they will be formatted using scientific notation through a Microsoft Jet workspace, but will appear as normal decimal values through an ODBCDirect workspace.


Version Property (DAO)

Version Property

  • Microsoft Jet workspace On the CdbDBEngine object, returns the version of DAO currently in use. On the CdbDatabase object, returns the version of Jet that created the .mdb file.

  • ODBCDirect workspace On the CdbDBEngine object, returns the version of DAO currently in use. On the CdbDatabase object, returns the version of the ODBC driver currently in use.

Syntax

CStringGetVersion(VOID);

Remarks

The return value is a version number, formatted as follows.

  • Microsoft Jet workspace represents the version number in the form "major.minor". For example, "3.0". The product version number consists of the version number (3), a period, and the release number (0).

  • ODBCDirect workspace represents the DAO version number in the form "major.minor", or represents the ODBC driver version number in the form "major.minor.build". For example, the CdbDBEngine.Version value of “3.5” indicated DAO version 3.5. A CdbDatabase object's Version value of 2.50.1032 indicates that the current instance of DAO is connected to ODBC version 2.5, build 1032.

In a Microsoft Jet workspace, the Version property of a CdbDatabase object corresponds to a version of the Microsoft Jet database engine, and doesn’t necessarily match the version number of the Microsoft product with which the database engine was included. For example, the Version property of a CdbDatabase object created with Microsoft Visual Basic 3.0 will be 1.1, not 3.0.

The following table shows which version of the database engine was included with various versions of Microsoft products.

Microsoft Jet Version (year released) | Microsoft Access | Microsoft Visual Basic | Microsoft Excel | Microsoft Visual C++
1.0 (1992) | 1.0 | N/A | N/A | N/A
1.1 (1993) | 1.1 | 3.0 | N/A | N/A
2.0 (1994) | 2.0 | N/A | N/A | N/A
2.5 (1995) | N/A | 4.0 (16-bit) | N/A | N/A
3.0 (1995) | ‘95 (7.0) | 4.0 (32-bit) | ‘95 (7.0) | 4.x
3.5 (1996) | ‘97 (8.0) | 5.0 | ‘97 (8.0) | 5.0


VisibleValue Property (DAO)

VisibleValue Property

Returns a value currently in the database that is newer than the OriginalValue property as determined by a batch update conflict (ODBCDirect workspaces only).

Syntax

COleVariantGetVisibleValue(VOID);

Remarks

This property contains the value of the field that is currently in the database on the server. During an optimistic batch update, a collision may occur where a second client modified the same field and record in between the time the first client retrieved the data and the first client's update attempt. When this happens, the value that the second client set will be accessible through this property.


Container Object, Containers Collection, and Document Object, Documents Collection Example (VC++)

This example enumerates the properties of all the Container and Document objects in the current database. See the properties listed in the Container and Document summary topics for additional examples.

CdbDBEngine      dbeng;
CdbDatabase      dbsCurrent;
CdbContainer   conTest;
CdbDocument      docTest;
int            i, j;

dbsCurrent = dbeng.OpenDatabase(_T("Northwind.mdb"));
for (i = 0; i < dbsCurrent.Containers.GetCount(); i++)
{
 conTest = dbsCurrent.Containers[i];
   printf(_T(">> Container: %s\n"), conTest.GetName());
   printf(_T("  Owner: %s\n"), conTest.GetOwner());
   printf(_T("  UserName: %s\n"), conTest.GetUserName());
   printf(_T("  Permissions: %s\n\n"), conTest.GetPermissions());
 for (j = 0; j < conTest.Documents.GetCount(); j++)
 {
      docTest = conTest.Documents[j];
      printf(_T(" > Document: %s\n"), docTest.GetName());
      printf(_T("  Owner: %s\n"), docTest.GetOwner());
      printf(_T("  Container: %s\n"), docTest.GetContainer());
      printf(_T("  UserName: %s\n)"), docTest.GetUserName());
      printf(_T("  Permissions: %08xd\n"),docTest.GetPermissions());
      printf(_T("  DateCreated: %s\n"), docTest.GetDateCreated());
      printf(_T("  LastUpdated: %s\n\n"), docTest.GetLastUpdated());
 }
}


Database Object, Databases Collection Example (VC++)

This example creates a new Database object and opens it (thereby appending it to the Databases collection) in the default Workspace object. Then it enumerates all the collections contained by each Database object and the properties of the new Database object and closes the new Database. See the methods and properties listed in the Database summary topic for additional examples.

CdbDBEngine         dbeng;
CdbWorkspace      wrkDefault;
CdbDatabase         dbsEnum, dbsTemp;
long            intOBJ, intDB;

wrkDefault = dbeng.Workspaces[0L];

dbsEnum = wrkDefault.CreateDatabase(_T("Northwind.mdb"), dbLangGeneral);
// Enumerate all open databases.
for (intDB = 0; wrkDefault.Databases.GetCount(); intDB++)
   {
   dbsTemp = wrkDefault.Databases[intDB];
   printf(_T("Enumeration of Database: %s\n"), dbsTemp.GetName());
   //   Enumerate containers.
   printf(_T("Container: Name, Owner"));
   for (intOBJ = 0; intOBJ < dbsTemp.Containers.GetCount(); intOBJ++)
      printf(_T("  %s, %s\n"), dbsTemp.Containers[intOBJ].GetName(),
            dbsTemp.Containers[intOBJ].GetOwner());

   // Enumerate query definitions.
   printf(_T("QueryDef: Name"));
   for (intOBJ = 0; intOBJ < dbsTemp.QueryDefs.GetCount(); intOBJ++)
      printf(_T("  %s\n"), dbsTemp.QueryDefs[intOBJ].GetName());

   // Enumerate Recordsets.
   // No output because no Recordset is open.
   printf(_T("\nRecordset: Name"));
   for (intOBJ = 0; intOBJ < dbsTemp.Recordsets.GetCount(); intOBJ++)
      printf(_T("  %s\n"), dbsTemp.Recordsets[intOBJ].GetName());

   // Enumerate relationships.
   printf(_T("\nRelation: Name, Table, ForeignTable"));
   for (intOBJ = 0; intOBJ < dbsTemp.Relations.GetCount(); intOBJ++)
      printf(_T("  %s, %s, %s\n"), dbsTemp.Relations[intOBJ].GetName(),
                  dbsTemp.Relations[intOBJ].GetTable(),
                  dbsTemp.Relations[intOBJ].GetForeignTable());

   // Enumerate table definitions.
   printf(_T("\nTableDef: Name, DateCreated"));
   for (intOBJ = 0; intOBJ < dbsTemp.TableDefs.GetCount(); intOBJ++)
      printf(_T(" %s, %s\n"), dbsTemp.TableDefs[intOBJ].GetName(),
                     dbsTemp.TableDefs[intOBJ].GetDateCreated());

   // Enumerate built-in properties of dbsEnum.
   printf(_T(" dbsEnum.Name: %s\n"), dbsEnum.GetName());
   printf(_T(" dbsEnum.CollatingOrder: %s\n"),
                        dbsEnum.GetCollatingOrder());
   printf(_T(" dbsEnum.Connect: %s\n"), dbsEnum.GetConnect());
   printf(_T(" dbsEnum.QueryTimeout: %s\n"),
                        dbsEnum.GetQueryTimeout());
   printf(_T(" dbsEnum.Transactions: %s\n"),
                        dbsEnum.GetTransactions());
   printf(_T(" dbsEnum.Updatable: %s\b"), dbsEnum.GetUpdatable());

   dbsEnum.Close;   // File remains on disk.
   }


DBEngine Object Example (VC++)

This example enumerates the collections of the DBEngine object. See the methods and properties of DBEngine for additional examples.

CdbDBEngine         dbeng;
CdbDatabase         dbsLudlow;
CdbWorkspace      wrkEnum;
long            intWSP;

// Enumerate all workspaces.

printf(_T("Workspaces: Name, UserName\n"));
for (intWSP = 0; dbeng.Workspaces.GetCount(); intWSP++)
{
   wrkEnum = dbeng.Workspaces[intWSP];
   printf(_T("  %s, %s"), wrkEnum.GetName(), wrkEnum.GetUserName());
}

// display built-in properties.
printf(_T("\nDBEngine.Version: %s\n"), dbeng.GetVersion());
printf(_T("DBEngine.LoginTimeout: %s\n"), dbeng.GetLoginTimeout());


Dynaset-Type Recordset Example (VC++)

This example creates a new dynaset-type Recordset object and opens it, appending it to the Recordsets collection in the default database. It then edits the record(s).

CdbDBEngine      dbeng;
CdbDatabase      dbsBiblio;
CdbRecordset      rstTitles;
CString         strSelect;

dbsBiblio = dbeng.OpenDatabase(_T("Biblio.mdb"));

strSelect = _T("Select * From Titles Where Title = 'Using SQL' ");
rstTitles = dbsBiblio.OpenRecordset(strSelect, dbOpenDynaset);

if (rstTitles.GetRecordCount() > 0 && rstTitles.GetUpdatable())
   {
   do
      {
      rstTitles.Edit();
      rstTitles.SetField(_T("Year Published"), COleVariant(1994L));
      rstTitles.Update();
      rstTitles.MoveNext();
      }
   while (rstTitles.GetEOF());
   }
else
   {
   printf(_T("No such title or table not updatable"));
   }
dbsBiblio.Close();


Field Object, Fields Collection Example (VC++)

This example creates a TableDef object and a Field object, appends the Field to the Fields collection in the new TableDef, and appends the TableDef to the TableDefs collection in the current database. The example enumerates all the fields in the new TableDef object and all the properties of the new Field. See the methods and properties listed in the Field summary topic for additional examples.

CdbDBEngine   dbeng;
CdbDatabase   dbsNorthwind;
CdbTableDef   tdfTest;
CdbField   fldTest;
long      i;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));
tdfTest = dbsNorthwind.CreateTableDef(_T("MyTable"));
fldTest = tdfTest.CreateField(_T("MyField"), dbDate);
tdfTest.Fields.Append(fldTest);
dbsNorthwind.TableDefs.Append(tdfTest);

// Get database name.
printf(_T("Database Name: %s\n"), dbsNorthwind.GetName());

// Enumerate all fields in tdfTest.
printf(_T("TableDefs: Name; Fields: Name\n"));

for (i = 0; tdfTest.Fields.GetCount(); i++)
   {
   printf(_T("  %s; %s\n"), tdfTest.GetName(), tdfTest.Fields[i].GetName());
   }
   printf(_T("\n"));
// Enumerate built-in properties of fldTest.
printf(_T("fldTest.Name: %s\n"), fldTest.GetName());
printf(_T("AllowZeroLength: %d\n"), fldTest.GetAllowZeroLength());
printf(_T("Attributes: %ld\n"), fldTest.GetAttributes());
printf(_T("CollatingOrder: %ld\n"), fldTest.GetCollatingOrder());
printf(_T("DefaultValue: %s\n"), fldTest.GetDefaultValue());
printf(_T("OrdinalPosition: %d\n"), fldTest.GetOrdinalPosition());
printf(_T("Required: %d\n"), fldTest.GetRequired());
printf(_T("Size: %ld\n"), fldTest.GetSize());
printf(_T("SourceField: %s\n"), fldTest.GetSourceField());
printf(_T("SourceTable: %s\n"), fldTest.GetSourceTable());
printf(_T("Type: %d\n"), fldTest.GetType());
printf(_T("ValidationRule: %s\n"), fldTest.GetValidationRule());
printf(_T("ValidationText: %s\n"), fldTest.GetValidationText());


Group Object, Groups Collection and User Object, Users Collection Example (VC++)

This example illustrates the use of the Group and User objects and the Groups and Users collections. First, it creates a new User object with the Name, PID, and Password property settings of "Pat Smith", "abc123DEF456", and "My Secret" and appends the object to the Users collection of the default Workspace object. Next, it creates a new Group object with the Name and PID property settings of "Accounting" and "UVW987xyz654" and appends the object to the Groups collection of the default Workspace object. Then the example adds user Pat Smith to the Accounting group. Finally, it enumerates the User and Group objects in the collections of the default Workspace object. See the methods and properties listed in the Group and User summary topics for additional examples.

CdbDBEngine         dbeng;
CdbWorkspace      wrkDefault;
CdbUser            usrTemp;
CdbGroup         grpTemp;
long            intI, intJ;

wrkDefault = dbeng.Workspaces[0L];

// Enumerate all users.
for (intJ = 0; intJ < wrkDefault.Users.GetCount(); intJ++)
   {
   usrTemp = wrkDefault.Users[intJ];
   printf(_T("Enumeration of User: %s\n\n"), usrTemp.GetName());

   // Enumerate groups.
   printf(_T("   Groups: \n"));
   for (intI = 0; intI < usrTemp.Groups.GetCount(); intI++)
      printf(_T("   %s\n"), usrTemp.Groups[intI].GetName());
   }
// Enumerate all groups.
printf(_T("\n------------------------------------\n\n"));
for (intJ = 0; intJ < wrkDefault.Groups.GetCount(); intJ++)
   {
   grpTemp = wrkDefault.Groups[intJ];
   printf("Enumeration of Groups: %s\n", grpTemp.GetName());
   // Enumerate users.
   printf(_T("   Users: \n"));
   for (intI = 0; intI < grpTemp.Users.GetCount(); intI++)
      printf(_T("   %s\n"), grpTemp.Users[intI].GetName());
   }


Index Object, Indexes Collection Example (VC++)

This example creates a new TableDef object and two new Field objects, appends the Field objects to the Fields collection in the new TableDef, and appends the TableDef to the TableDefs collection in the database. Then it creates a new primary Index object, includes the two Field objects in it, and appends the Index to the Indexes collection of the TableDef. Finally, the example enumerates the Index objects in the current database. See the methods and properties listed in the Index summary topic for additional examples.

CdbDBEngine      dbeng;
CdbDatabase      dbsDefault;
CdbTableDef      tdfTest;
CdbField      fldOne, fldTwo;
CdbIndex      idxPrimary;
long         I;

// Get workspace and database.
dbsDefault = dbeng.OpenDatabase(_T("Northwind.mdb"));

// Create table with two fields.
tdfTest = dbsDefault.CreateTableDef(_T("MyTable"));
fldOne = tdfTest.CreateField(_T("Field1"), dbLong);
fldOne.SetRequired(TRUE);   // No Null values allowed.
tdfTest.Fields.Append(fldOne);
fldTwo = tdfTest.CreateField(_T("Field2"), dbLong);
fldTwo.SetRequired(TRUE);   // No Null values allowed.
tdfTest.Fields.Append(fldTwo);
dbsDefault.TableDefs.Append(tdfTest);

// Create primary index for those two fields.
idxPrimary = tdfTest.CreateIndex(_T("MyIndex"));
idxPrimary.SetPrimary(TRUE);
fldOne = tdfTest.CreateField(_T("Field1"));
idxPrimary.Fields.Append(fldOne);
fldTwo = tdfTest.CreateField(_T("Field2"));
idxPrimary.Fields.Append(fldTwo);
tdfTest.Indexes.Append(idxPrimary);

// Enumerate index and its fields.
printf(_T("Index: %s\n"), idxPrimary.GetName());
printf(_T("  Required: %d\n"), idxPrimary.GetRequired());
printf(_T("  IgnoreNulls: %d\n"), idxPrimary.GetIgnoreNulls());
printf(_T("  Primary: %d\n"), idxPrimary.GetPrimary());
printf(_T("  Clustered: %d\n"), idxPrimary.GetClustered());
printf(_T("  Unique: %d\n"), idxPrimary.GetUnique());
printf(_T("  Foreign: %d\n"), idxPrimary.GetForeign());

printf(_T("\nFields in Index:\n"));
for( I = 0; I < idxPrimary.Fields.GetCount(); I++)
   printf(_T(" %s\n"), idxPrimary.Fields[I].GetName());

This example opens a table-type Recordset and selects an index for the Recordset. By setting an index, the Microsoft Jet database engine returns records in the order specified by the index. Without an index, table-type Recordset objects return records from the database table in no particular order.

CdbDBEngine         dbeng;
CdbDatabase         dbsDefault;
CdbRecordset      rstTitles;

// Get workspace and database.
dbsDefault = dbeng.OpenDatabase(_T("Northwind.mdb"));
rstTitles = dbsDefault.OpenRecordset(_T("Titles"));
rstTitles.SetIndex(_T("MyIndex"));
   .
   .
   .


Parameter Object, Parameters Collection Example (VC++)

This example sets two query parameters for a hypothetical parameter query named “ParamQuery,” executes the query by opening a Recordset from the QueryDef, and then prints the properties of each parameter. Note that this query does not actually exist in the Northwind sample database. The parameter data types are of type Date. See the methods and properties listed in the Parameter summary topic for additional examples.

CdbDBEngine         dbeng;
CdbDatabase         dbsCurrent;
CdbQueryDef         qdfParam;
CdbParameter      prmEnum;
CdbRecordset      rstParam;
long            X;

dbsCurrent = dbeng.OpenDatabase(_T("Northwind.mdb"));
qdfParam = dbsCurrent.QueryDefs[_T("ParamQuery")];

// Set parameters.
qdfParam.Parameters[_T("Order Date")].SetValue(COleVariant(_T("10/11/94")));
qdfParam.Parameters[_T("Ship Date")].SetValue(COleVariant(_T("11/4/94")));

rstParam = qdfParam.OpenRecordset();

// Show parameter properties.
for (X = 0; X < qdfParam.Parameters.GetCount(); X++)
   {
   prmEnum = qdfParam.Parameters[X];
   printf("%s %d\n", prmEnum.GetName(),   // Print parameter properties.
                  prmEnum.GetType());
   }

rstParam.Close;


Property Object, Properties Collection Example (VC++)

This example creates a user-defined property for the current database, sets its Type and Value properties, and appends it to the Properties collection of the database. Then the example enumerates all properties in the database. See the properties listed in the Property summary topic for additional examples.

CdbDBEngine      dbeng;
CdbWorkspace    wrkDefault;
CdbDatabase   db;
CdbProperty   prpUserDefined, prpEnum;
COleVariant   var("This is a user-defined property.", VT_BSTRT),
         varBstr;
int         i;

// Open the database.
db = dbeng.OpenDatabase(_T("Northwind.mdb"));

// Create user-defined property.
prpUserDefined = db.CreateProperty();

// Set properties of new property.
prpUserDefined.SetName("UserDefinedProperty");
prpUserDefined.SetType(dbText);
prpUserDefined.SetValue((LPVARIANT)var);

// Append property to current database.
db.Properties.Append(prpUserDefined);

// Enumerate all properties of current database.
printf("Properties of Database %s\n", db.GetName());
for (i = 0; i < db.Properties.GetCount(); i ++)
   {
   prpEnum = db.Properties[i];
   printf(" Properties(%d)\n", i);
   printf("  Name: %s\n",  prpEnum.GetName());
   printf("  Type: %d\n", prpEnum.GetType());

   // Change type of variant to BSTR for printing.
   try
      {
      varBstr.ChangeType(VT_BSTR, var);
      printf("  Value: %s\n", (LPCSTR)varBstr.pbstrVal);
      }
   catch (CdbException e)
      {
      printf("  Value: Value could not be converted to a string\n");
      }

   printf("  Inherited: %d\n", prpEnum.GetInherited());
   }

This example shows how you can set an application-defined property (or any user-defined property that may not yet exist) without causing a run-time error. The example sets an arbitrary property of a Field object. The return value of the function is True if the value was properly set. The return value is False if an unexpected error occurs when the property is set. See the properties listed in the Property summary topic for additional examples.

LONG SetFieldProperty(
   CdbDBEngine &dbe,
   CdbField &fldPropVal,
   LPCTSTR pstrName,
   int nType,
   LPVARIANT pvarValue)
   {
#define ERR_PROPERTY_NONEXISTENT 3270
   CdbProperty prpUserDefined;
   LONG      lErr;

   // Set the field property value.
   try
      {
      fldPropVal.Properties[pstrName].SetValue(pvarValue);
      }

   catch (CdbException exSetPropValue)
      {
      lErr = dbe.Errors[(LONG)0].GetNumber();
      if (lErr != ERR_PROPERTY_NONEXISTENT)
         {
         return lErr;
         }
      else
         {
         // Create Property object, setting Name, Type, and Value properties.
         try
            {
            prpUserDefined = fldPropVal.CreateProperty(pstrName, nType, pvarValue);
            fldPropVal.Properties.Append(prpUserDefined);
            }
         catch (CdbException exUDP)
            {
            return dbe.Errors[(LONG)0].GetNumber();
            }
         }
      }
   return NOERROR;
   }

int main()
   {
   CdbDBEngine dbeng;
   CdbDatabase db;
   CdbTableDef td;
   CdbField   fld;
   COleVariant var("This is a user-defined property.", VT_BSTRT);
   LONG lErr;

   // Open the database.
   db = dbeng.OpenDatabase(_T("Northwind.mdb"));

   // Get a reference on a table.
   td = db.TableDefs[_T("Employees")];

   // Get a reference on the 'name' field.
   fld = td.Fields[_T("Last Name")];

   // Set the field property.
   lErr = SetFieldProperty(dbeng, fld, _T("foo"), dbText, (LPVARIANT)var);

   return (lErr == NOERROR) ? 0 : -1;
   }


QueryDef Object, QueryDefs Collection Example (VC++)

This example creates a new QueryDef object and appends it to the QueryDefs collection in the current database. Then the example enumerates all the QueryDef objects in the database and all the properties of the new QueryDef. See the methods and properties listed in the QueryDef summary topic for additional examples.

CdbDBEngine   dbeng;
CdbDatabase   db;
CdbQueryDef   qdfTest;
COleVariant   var("This is a user-defined property.",
      VC_BSTRT);
int         i;

// Open the database.
db = dbeng.OpenDatabase(_T("Northwind.mdb"));

// Create a query definition.
qdfTest = db.CreateQueryDef(_T("This is a test"));

// Enumerate QueryDef objects.
for (i = 0; i < db.QueryDefs.GetCount(); i++)
{
   printf("%s\n", db.QueryDefs[i].GetName());
}

// Enumerate built-in properties of qdfTest.
printf("qdfTest.Name: %s\n", qdfTest.GetName());
printf("qdfTest.DateCreated: %s\n", qdfTest.GetDateCreated().Format());
printf("qdfTest.LastUpdated: %s\n", qdfTest.GetLastUpdated().Format());
printf("qdfTest.SQL: %s\n", qdfTest.GetSQL());
printf("qdfTest.ODBCTimeout: %d\n", qdfTest.GetODBCTimeout());
printf("qdfTest.Updatable: %d\n", qdfTest.GetUpdatable());
printf("qdfTest.Type: %d\n", qdfTest.GetType());
printf("qdfTest.Connect: %s\n", qdfTest.GetConnect());
printf("qdfTest.ReturnsRecords: %d\n", qdfTest.GetReturnsRecords());

// Delete the query definition.
db.QueryDefs.Delete(_T("This is a test"));


Recordset Object, Recordsets Collection Example (VC++)

This example creates a new Recordset object and opens it (thereby appending it to the Recordsets collection) in the default database. Then the example enumerates all the Recordset objects in the current database and all the fields in each Recordset object and closes the new Recordset. See the methods and properties in the Recordset summary topic for additional examples.

CdbDBEngine      dbeng;
CdbDatabase      db;
CdbRecordset   rstOrders, rstTemp;
int            nRS, nFld;

// Open the database.
db = dbeng.OpenDatabase(_T("Northwind.mdb"));

// Open a Recordset.
rstOrders = db.OpenRecordset("Orders", dbOpenSnapshot);

// Enumerate Recordsets.
for (nRS = 0; nRS < db.Recordsets.GetCount(); nRS++)
   {
   rstTemp = db.Recordsets[nRS];
   printf("Recordset object(%d): \n", nRS, rstTemp.GetName());

   // Enumerate fields.
   printf("Fields: Name, Type, Value\n");
   for (nFld = 0; nFld < rstTemp.Fields.GetCount(); nFld++)
      {
      printf("  %s, %s", rstTemp.Fields[nFld].GetName(),
      rstTemp.Fields[nFld].GetType());
      if (rstTemp.Fields[nFld].GetType() == dbText)
         printf(", %s\n", rstTemp.Fields[nFld].GetValue());
      else
         printf("\n");
      }
   }

db.Close();


Relation Object, Relations Collection Example (VC++)

This example creates a one-to-many relationship between single fields in two tables. Because referential integrity is enforced for the relationship, an index is created for the primary table. See the methods and properties listed in the Relation summary topic for additional examples.

CdbDBEngine   dbeng;
CdbDatabase   db;
CdbRelation   qdfTest;
CdbTableDef   tdfReferenced, tdfReferencing;
CdbField   fldPrimeKey;
CdbIndex   idxUnique;
CdbRelation   relEnforced;
int         nFld;

// Open the database.
db = dbeng.OpenDatabase(_T("Northwind.mdb"));

// Create referenced table with primary key.
tdfReferenced = db.CreateTableDef(_T("Referenced"));
fldPrimeKey = tdfReferenced.CreateField(_T("PrimaryKey"), dbLong);
tdfReferenced.Fields.Append(fldPrimeKey);

// Create unique index for enforced referential integrity.
idxUnique = tdfReferenced.CreateIndex(_T("UniqueIndex"));
idxUnique.SetPrimary(TRUE); // No Null values allowed.

fldPrimeKey = tdfReferenced.CreateField(_T("PrimaryKey"));
idxUnique.Fields.Append(fldPrimeKey);
tdfReferenced.Indexes.Append(idxUnique);
db.TableDefs.Append(tdfReferenced);

// Create referencing table with foreign key.
tdfReferencing = db.CreateTableDef(_T("Referencing"));
fldPrimeKey = tdfReferencing.CreateField(_T("ForeignKey"), dbLong);
tdfReferencing.Fields.Append(fldPrimeKey);
db.TableDefs.Append(tdfReferencing);

// Create one-to-many relationship & enforce referential integrity.
relEnforced = db.CreateRelation(_T("EnforcedOneToMany"));
relEnforced.SetTable(_T("Referenced"));
relEnforced.SetForeignTable(_T("Referencing"));

// Don't set either dbRelationUnique or dbRelationDontEnforce.
relEnforced.SetAttributes(0);
fldPrimeKey = relEnforced.CreateField(_T("PrimaryKey"));
fldPrimeKey.SetForeignName(_T("ForeignKey"));
relEnforced.Fields.Append(fldPrimeKey);
db.Relations.Append(relEnforced);

// Enumerate relation and its fields.
printf("Relation: %s\n", relEnforced.GetName());
printf("  Primary Table: %s\n", relEnforced.GetTable());
printf("  Foreign Table: %s\n", relEnforced.GetForeignTable());
printf("  Attributes: %ld\n", relEnforced.GetAttributes());
printf("Fields in Relation: Primary, Foreign");
for (nFld = 0; nFld < relEnforced.Fields.GetCount(); nFld++)
   {
   fldPrimeKey = relEnforced.Fields[nFld];
   printf("  %s", fldPrimeKey.GetName());
   printf(", %s\n", fldPrimeKey.GetForeignName());
   }

db.Relations.Delete("EnforcedOneToMany");
db.TableDefs.Delete("Referenced");
db.TableDefs.Delete("Referencing");


Snapshot-Type Recordset Example (VC++)

This example creates a new snapshot-type Recordset object and opens it, appending it to the Recordsets collection in the default database. It then finds a record and prints it.

CdbDBEngine      dbeng;
CdbDatabase      db;
CdbRecordset   rstTitles;

// Open the database.
db = dbeng.OpenDatabase(_T("Biblio.mdb"));

// Open a recordset on Titles table.
rstTitles = db.OpenRecordset("Titles", dbOpenSnapshot);
if (rstTitles.GetRecordCount() > 0)
   {
   rstTitles.FindFirst("Title Like '*VBSQL*'");  // Any title on VBSQL
   while (rstTitles.GetNoMatch() == TRUE)
      {
      printf("%s\n", rstTitles.Fields[_T("Title")]);
      rstTitles.FindNext(_T("Title Like '*VBSQL*'"));
      }
   }
else
   {
   printf("No such title\n");
   }

db.Close();


Table-Type Recordset Example (VC++)

This example opens a table-type Recordset and selects an index for the Recordset. By setting an index, the Microsoft Jet database engine returns records in the order specified by the index. Without an index, table-type Recordset objects return records from the database table in no particular order.

CdbDBEngine      dbeng;
CdbDatabase      db;
CdbRecordset   rstTitles;

// Open the database.
db = dbeng.OpenDatabase(_T("Biblio.mdb"));

rstTitles = db.OpenRecordset("Titles", dbOpenTable);
rstTitles.SetIndex(_T("MyIndex"));
...
...
...


TableDef Object, TableDefs Collection Example (VC++)

This example creates a new TableDef object, adds a Field object to it, and appends the TableDef to the TableDefs collection in the current database. Then the example enumerates all the TableDef objects in the current database and all the properties of the new TableDef. See the methods and properties listed in the TableDef summary topic for additional examples.

CdbDBEngine      dbeng;
CdbDatabase      db;
CdbTableDef      tdfEnum;
CdbField      fldDate;
int         nFld, nIdx;

// Open the database.
db = dbeng.OpenDatabase(_T("Northwind.mdb"));

// Create a tabledef.
tdfEnum = db.CreateTableDef("MyTable");
fldDate = tdfEnum.CreateField("Date", dbDate);
tdfEnum.Fields.Append(fldDate);
db.TableDefs.Append(tdfEnum);

// Get database name.
printf("Database Name: %s\n", db.GetName());

// Enumerate all fields in tdfEnum.
printf("TableDef: Name; Field: Name\n");
for (nFld = 0; nFld < tdfEnum.Fields.GetCount(); nFld++)
   {
   printf("  %s", tdfEnum.GetName());
   printf("; %s\n", tdfEnum.Fields[nFld].GetName());
   }

// Enumerate all indexes in tdfEnum.
printf("TableDef: Name; Index: Name\n");
for (nIdx = 0; nIdx < tdfEnum.Indexes.GetCount(); nIdx++)
   {
   printf("  %s", tdfEnum.GetName());
   printf("; %s\n", tdfEnum.Indexes[nIdx].GetName());
   }

// Enumerate built-in properties of tdfEnum.
printf("tdfEnum.Name: %s\n", tdfEnum.GetName());
printf("tdfEnum.Attributes: %ld\n", tdfEnum.GetAttributes());
printf("tdfEnum.Connect: %s\n", tdfEnum.GetConnect());
printf("tdfEnum.DateCreated: %s\n", tdfEnum.GetDateCreated().Format());
printf("tdfEnum.LastUpdated: %s\n", tdfEnum.GetLastUpdated().Format());
printf("tdfEnum.RecordCount: %ld\n", tdfEnum.GetRecordCount());
printf("tdfEnum.SourceTableName: %s\n", tdfEnum.GetSourceTableName());
printf("tdfEnum.Updatable: %d\n", tdfEnum.GetUpdatable());
printf("tdfEnum.ValidationRule: %s\n", tdfEnum.GetValidationRule());
printf("tdfEnum.ValidationText: %s\n", tdfEnum.GetValidationText());


Workspace Object, Workspaces Collection Example (VC++)

This example creates a new Workspace and appends it to the Workspaces collection. It assumes that the user JustAUser with a password of Secret has already been created. The example enumerates the collections of each Workspace object and finally closes the new Workspace. See the methods and properties of the Workspace object or Workspaces collection for additional examples.

CdbDBEngine      dbeng;
CdbWorkspace   wrkNew, wrkEnum;
CdbDatabase      db;
int         nWrk, nDb, nUsr, nGrp;

// Open the database.
db = dbeng.OpenDatabase(_T("Northwind.mdb"));

// Create new workspace and add it to collection.
wrkNew = dbeng.CreateWorkspace("NewWorkspace", "JustAUser", "");
dbeng.Workspaces.Append(wrkNew);

// Enumerate all workspaces.
for (nWrk = 0; nWrk < dbeng.Workspaces.GetCount(); nWrk++)
   {
   wrkEnum = dbeng.Workspaces[nWrk];
   printf("\nEnumeration of Workspaces(%d): %s\n", nWrk, wrkEnum.GetName());
   // Enumerate databases.
   printf("Databases: Name\n");
   for (nDb = 0; nDb < wrkEnum.Databases.GetCount(); nDb++)
      printf("  %s\n", wrkEnum.Databases[nDb].GetName());

   // Enumerate all user accounts.
   printf("Users: Name\n");
   for (nUsr = 0; nUsr < wrkEnum.Users.GetCount(); nUsr++)
      printf("  %s\n", wrkEnum.Users[nUsr].GetName());

   // Enumerate all group accounts.
   printf("Groups: Name\n");
   for (nGrp = 0; nGrp < wrkEnum.Groups.GetCount(); nGrp++)
      printf("  %s\n", wrkEnum.Groups[nGrp].GetName());
   }

// Enumerate built-in properties of wrkNew.
printf("wrkNew.Name: %s\n", wrkNew.GetName());
printf("wrkNew.UserName: %s\n", wrkNew.GetUserName());
wrkNew.Close();


AddNew Method, LastModified Property Example (VC++)

This example queries for a first and last name and adds them as a new record to the Employee database.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\AddNew.cpp.


Append Method Example (VC++)

The example appends three fields to a Fields collection then deletes them.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\Append.cpp.


AppendChunk, FieldSize, GetChunk Methods Example (VC++)

This example uses the AppendChunk and GetChunk methods to copy data to another record, 32K at a time. Afterwards, the new record is deleted.

In a real application, you might use a procedure like this to copy an employee record (including the employee's photo) from one table to another. Note that all the chunk manipulation takes place within a single AddNew-Update sequence.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\AppendChunk.cpp.


BeginTrans, CommitTrans, Rollback Methods Example (VC++)

This example loops through a recordset and asks if the user wants to change the job title of each sales representatives in the Employees table. After the BeginTrans method starts a transaction that isolates all the changes made to the Employees table, the CommitTrans method saves the changes. Later, the Rollback method is used to undo changes that were saved using the Update method.

One or more table pages remain locked while the user decides whether or not to accept the changes. For this reason, this technique isn't recommended, but is shown only as an example.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\BeginTrans.cpp.


CancelUpdate Method Example (VC++)

The first example uses CancelUpdate to abort an AddNew. The second example uses CancelUpdate to abort an Edit.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\CancelUpdate1.cpp and CancelUpdate2.cpp.


Clone Method Example (VC++)

This example creates a Recordset object based on the Orders table in the Northwind database and uses the Clone method to create two more Recordset objects. Each Recordset object has its own current record that can be moved independently of the other.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\Clone.cpp.


Close Method Example (VC++)

This example opens and then closes a database and a table-type Recordset object for the Customers table in the database.

CdbDBEngine      dbeng;
CdbDatabase      dbsdb;
CdbRecordset      dbrs;

dbsdb = dbeng.OpenDatabase(_T("Northwind.mdb"));
dbrs = dbsdb.OpenRecordset(_T("Customers"));
dbrs.Close();
dbsdb.Close();


CompactDatabase Method Example (VC++)

The first example uses CompactDatabase to create a compact version of the Northwind database that uses the Korean language collating order. The second example uses CompactDatabase to create a compact and encrypted Microsoft Jet 2.0 version of a Microsoft Jet version 1.1 database.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\CompactDatabase1.cpp and CompactDatabase2.cpp.


CreateDatabase Method Example (VC++)

This example uses CreateDatabase to create a new, encrypted Database object. The example enumerates the properties of the new database, and then closes it.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\CreateDatabase.cpp.


CreateField Method Example (VC++)

This example creates three new Field objects, and then enumerates their properties.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\CreateField.cpp.


CreateGroup Method Example (VC++)

This example creates a new Group object and enumerates its properties.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\CreateGroup.cpp.


CreateIndex Method Example (VC++)

This example creates a new Index object and enumerates its properties.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\CreateIndex.cpp.


CreateProperty Method Example (VC++)

This example attempts to set the value of a property. If the property doesn't exist, a new Property object is created. Then the database object's Properties collection is enumerated.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\CreateProperty.cpp.


CreateQueryDef Method Example (VC++)

This example creates a temporary QueryDef on the Employees table and a permanent QueryDef on the Categories table, and then prints a report for each of them.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\CreateQueryDef.cpp.


CreateRelation Method Example (VC++)

This example creates a new Relation object between the Employees and Departments tables. It then adds a field to the Relation object, and then generates a report describing properties governing the relation.

By setting the dbRelationUpdateCascade attribute, the Microsoft Jet database engine changes the foreign table if a corresponding value changes in the Primary table.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\CreateRelation.cpp.


CreateTableDef Method Example (VC++)

This example creates a new TableDef object in the Northwind.mdb database.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\CreateTableDef.cpp.


CreateUser Method Example (VC++)

This example creates a new User object.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\CreateUser.cpp.


CreateWorkspace Method Example (VC++)

This example creates ODBC and Microsoft Jet Workspace objects, enumerates the two Workspaces collections, and then enumerates their properties.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\CreateWorkspace.cpp.


Delete Method Example (VC++)

This example seeks a record in a Recordset and deletes it.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\Delete.cpp.


OpenRecordset, Edit, Update Methods Example (VC++)

This example edits and updates the first and last names of a selected record.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\Edit.cpp.

Note Sometimes using SQL can be the most efficient way to perform a task. For example, you could use the following code to locate each record whose Title field satisfies the search criteria and then change the job title.

CString strSQL = _T("Update Employees Set Title = 'Account Executive' WHERE Title = 'Sales Representative' ");
dbsNorthwind.Execute( strSQL );


Execute Method Example (VC++)

This example uses a Data control to execute an action query that updates all titles that have no value in the ISBN column in the Titles table. If there is an error, all changes are rolled back.

CString strSQL = _T("DELETE FROM Titles WHERE ISBN IS NULL");
dbsBiblio.Execute( strSQL, dbFailOnError );


FindFirst, FindLast, FindNext, FindPrevious Methods Example (VC++)

This example navigates through a recordset by asking the user whether to use FindFirst, FindLast, FindNext, or FindPrevious.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\FindFirst.cpp.


GetRows Method Example (VC++)

The following example uses an SQL statement to retrieve three fields from an Employees table into a Recordset object. It then uses the GetRows method to retrieve as many records as the user specifies, and stores the selected records in a two-dimensional array. Each record is then printed.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\GetRows.cpp.


Idle Method Example (VC++)

This example calls the Idle method to release unneeded locks, force pending writes, and refresh memory with the current data in the database.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\Idle.cpp.


MakeReplica Method Example (VC++)

This example describes a function which calls the MakeReplica method to create a replica of the specified database.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\MakeReplica.cpp.


Move Method Example (VC++)

This example navigates through a Recordset moving forward or backward the requested number of records.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\Move.cpp.


MoveFirst, MoveLast, MoveNext, MovePrevious Methods Example (VC++)

This example navigates through a recordset by asking the user whether to use MoveFirst, MoveLast, MoveNext, or MovePrevious.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\MoveFirst.cpp.


NewPassword Method Example (VC++)

This example asks you for a new password for a new user named Pat Smith.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\NewPassWord.cpp.


NextRecordset Method Example (VC++)

DAO 3.5 supports issuing multiple SELECTs in a signal statement. This example shows how to get each of the returned Recordsets.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\NextRecordset.cpp.


OpenConnection Method Example (VC++)

This example uses the OpenConnection method to open several ODBCDirect Connection objects.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\OpenConnection.cpp.


OpenDatabase Method Example (VC++)

This example opens a Microsoft Jet database and two Microsoft Jet-connected ODBC data sources, and then enumerates their properties.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\OpenDatabase.cpp.


OpenRecordset Method Example (VC++)

This example opens several different types of Recordset objects.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\OpenRecordset.cpp.


OpenRecordset Method Example (VC++)

PopulatePartial Method Example (VC++)

This example demonstrates the PopulatePartial replication method in conjunction with the SetReplicaFilter property and the Synchronize method.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\PopulatePartial.cpp.


Refresh Method Example (VC++)

This example use the Refresh method on the Fields collection of a TableDef after rearranging the OrdinalPosition property of the fields.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\Refresh.cpp.


RefreshLink Method Example (VC++)

This example changes the connection to an ODBC data source then uses RefreshLink to make the information available.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\RefreshLink.cpp.


RegisterDatabase Method Example (VC++)

This example queries you for a description of an ODBC database then adds that to the information entered in the Windows Registry.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\RegisterDatabase.cpp


RepairDatabase Method Example (VC++)

This example attempts to repair a database named Northwind.mdb.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\RepairDatabase.cpp.


Requery Method Example (VC++)

The first example uses Requery to refresh a recordset after the underlying data is changed. The second example uses Requery to refresh a recordset after an underlying query parameter is changed.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\RequeryX1.cpp and RequeryX2.cpp.


Seek Method Example (VC++)

This example queries you for a product ID, seeks the corresponding record, and then displays information about the product.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\Seek.cpp.

The following example uses Seek to locate the first record in the Publishers table where the PubID field is 3, using the existing primary key index.

CdbDBEngine dben;
CdbDatabase dbsBiblio;
CdbRecordset rstPublishers;

dbsBiblio = dben.OpenDatabase(_T("Biblio.mdb"));
rstPublishers = dbsBiblio.OpenRecordset(_T("Publishers"));
rstPublishers.SetIndex(_T("PrimaryKey"));
rstPublishers.Seek(_T("="), 1, COleVariant((long) 3));
if (rstPublishers.GetNoMatch())
 {
 //...
 }

The following example uses the OpenDatabase method to directly open an installable ISAM database and then uses Seek to locate a record in a table in that database.

CdbDBEngine dben;
CdbDatabase dbsFoxData;
CdbRecordset rstParts;
CdbBookmark bk;
COleVariant var;

dbsFoxData = dben.OpenDatabase(_T("C:\\FoxData"),    FALSE, FALSE, _T("Fox 2.5;"));
rstParts = dbsFoxData.OpenRecordset(_T("parts.dbf"), dbOpenTable);

// Choose record order and Seek index.
rstParts.SetIndex(_T("PartNameIndex"));
bk = rstParts.GetBookmark();

// Search for first instance of a chosen part.
rstParts.Seek (_T("="), 1, COleVariant("Framis Lever",
   VT_BSTRT));
if (rstParts.GetNoMatch())     // Test for success.
 rstParts.SetBookmark(&bk);   // Seek not successful.
else
// Seek worked; use current record.
 var = rstParts.GetField(_T("PartName"));


SetOption Method Example (VC++)

This example demonstrates using SetOption to change run-time registry settings.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\SetOption.cpp.


Synchronize Method Example (VC++)

This example demonstrates four applications of the Synchronize method.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\Synchronize.cpp.


Update Method Example (VC++)

This first example edits the first and last name in a record, then asks whether you want to use Update to commit the change or CancelUpdate to reject it.

This second example adds a new record, then asks whether you want to use Update to commit the change or CancelUpdate to reject it.

See How to Build the DAO Method Samples.

On the MSDN Library discIf you have installed the DAO SDK, see Samples\dbdaoInstallDirectory\DAOSDK\SAMPLES\Update1.cpp and Update2.cpp.


AbsolutePosition Property Example (VC++)

This example positions the current record to the nth record in a dynaset-type Recordset object.

int MoveToRecord(long lPosition, CdbRecordset &rstTest)
{
   rstTest.MoveLast();
   if (rstTest.GetRecordCount() > lPosition)
   {
      rstTest.SetAbsolutePosition(lPosition);
      return TRUE;
   }
   else
      return FALSE;
}


BOF and EOF Properties Example (VC++)

This example uses the BOF and EOF properties to find the beginning and end of an Orders table. The example moves through the records from the beginning of the file to the end and then from the end to the beginning. Notice that there is no current record immediately following the first loop.

CdbDBEngine         dbeng;
CdbDatabase         dbsNorthwind;
CdbRecordset      rstOrders;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));
rstOrders = dbsNorthwind.OpenRecordset(_T("Orders"));   //open RS
while (!rstOrders.GetEOF())   // loop through all records
{
   // DO SOMETHING WITH THE RECORD
   rstOrders.MoveNext();      // move to the next record
}
rstOrders.MoveLast();         // move to the last record
while (!rstOrders.GetBOF())   // loop through all records
{
   // DO SOMETHING WITH THE RECORD
   rstOrders.MovePrevious();   // move to the previous record
}
rstOrders.Close();
dbsNorthwind.Close();


Bookmark and Bookmarkable Properties Example (VC++)

This example shows how you can save your place in a Recordset by saving a bookmark. Once saved, this bookmark can be applied to the Bookmark property to reposition the current record pointer to any location in the Recordset. The FindYear function works with the Biblio.mdb database. It looks up all titles in a given Recordset published in a given year and fills a string array with the bookmarks of any records that match.

int FindYear(int intYear, CdbRecordset &rstBooks,
         CdbBookmark *abkRecord)
{
   int intCount = 0;
   CString   strCriteria;
   //
   strCriteria.Format(
         _T("[Year Published] = %d"), intYear );
   rstBooks.FindFirst(strCriteria);
   while (!rstBooks.GetNoMatch() &&
             rstBooks.GetBookmarkable())
   {
      abkRecord[intCount++] = rstBooks.GetBookmark();
      rstBooks.FindNext(strCriteria);
   }
   return intCount;
}


CacheSize and CacheStart Properties Example (Client/Server) (VC++)

This example moves through all records in a Recordset twice; once with no cache and once with a 50 record cache. The example then displays the performance statistics for the uncached and cached runs through the Recordset.

/*
CacheStart/CacheSize Properties:
This example moves through all records in a Recordset twice; once with no cache and once with a 50
record cache.  The example then displays the performance statistics for the uncached and cached runs
through the Recordset.
*/

#include      <stdio.h>
#include      <time.h>
#include      <afxole.h>
#include      <dbdao.h>
#include      <dbdaoerr.h>

CdbDBEngine      dben;
CdbDatabase       dbsPubs;
CdbWorkspace    wspDefault;
CdbTableDef       tdfPerformanceTest;
CdbRecordset      rstRemote;
CString         strNoCache, strCache;
time_t            tmStart, tmNoCache, tmCache;
COleVariant      vVal;
LPTSTR            szPurpose =
                  _T("This example moves through ")
                  _T("all records in the Recordset ")
                  _T("twice;\n")
                  _T("once with no cache and ")
                  _T("once with a 50 record cache."),
               szAnnounce = _T(
                  "Caching Performance Results:\n"),
               szAnnounceNoCache = _T(
                  "Time without caching: %ld\n"),
               szAnnounceCache = _T(
                  "Time with 50 record cache: %ld\n");

wspDefault = dben.Workspaces[0L];
dbsPubs = wspDefault.OpenDatabase(_T("PUBLISH.mdb"));
tdfPerformanceTest =    dbsPubs.CreateTableDef(_T("TestData"));
tdfPerformanceTest.SetConnect(
  _T("ODBC;DATABASE=pubs;UID=sa;PWD=;DSN=Publishers"));
tdfPerformanceTest.SetSourceTableName(
  _T("dbo.roysched"));
dbsPubs.TableDefs.Append(tdfPerformanceTest);
rstRemote = dbsPubs.OpenRecordset(_T("TestData"));

// Announce purpose of this test.
printf(szPurpose);

// Start uncached run.
tmStart = time(NULL);
for (int x = 0; x < 2; x++)
{
rstRemote.MoveFirst();
while (!rstRemote.EOF())
   {
   vVal = rstRemote.GetField(0L);
   rstRemote.MoveNext();
   }
}
tmNoCache = time(NULL) - tmStart;

// Start cached run.
rstRemote.SetCacheSize(50);
tmStart = time(NULL);
for (int x = 0; x < 2; x++)
{
rstRemote.MoveFirst();
rstRemote.SetCacheStart(rstRemote.GetBookmark());
rstRemote.FillCache();
while (!rstRemote.EOF())
   {
   vVal = rstRemote.GetField(0L);
   rstRemote.MoveNext();
   }
}
tmCache = time(NULL) - tmStart;

// Display performance results.
printf(szAnnounce);
printf(szAnnounceNoCache, (long)tmNoCache);
printf(szAnnounceCache, (long)tmCache);

rstRemote.Close();
dbsPubs.Close();


ConflictTable Property Example (VC++)

This example shows how to use the ConflictTable property to resolve update conflicts.

void ResolveConflict( CdbDatabase& dbs )
{
CdbTableDef         tdfTest;
CdbRecordset      rstConflict;
CString            strTable;
long            lCt, lMaxCt;
//
lMaxCt = dbs.TableDefs.GetCount();
for (lCt = 0; lCt < lMaxCt; lCt++)
   {
   tdfTest = dbs.TableDefs[lCt];
   strTable = tdfTest.GetConflictTable();
   if(!strTable.IsEmpty())
      {
      rstConflict = dbs.OpenRecordset(
                     (LPCTSTR)strTable));
      // Process each record
      rstConflict.MoveFirst();
      while (!rstConflict.GetEOF())
         {
         // Do conflict resolution.
         // Remove conflicting record when finished.
         rstConflict.Delete();
         rstConflict.MoveNext();
         }
      rstConflict.Close();
      }
   }
}


Connect and SourceTableName Properties Example (VC++)

This example creates a TableDef object in the specified database; sets its Connect, Name, and SourceTableName properties; and then appends it to the TableDefs collection.

CdbDBEngine      dbeng;
CdbDatabase      dbsLocal;
CdbTableDef      tdfPDXAuthor;

dbsLocal = dbeng[0L].OpenDatabase(_T("Northwind.mdb"));

tdfPDXAuthor = dbsLocal.CreateTableDef(_T("PDXAuthor"));
// Paradox table 'Author' in Database C:\PDX\Publish
tdfPDXAuthor.SetConnect(_T("Paradox 4.X;DATABASE=C:\\PDX\\PUBLISH"));
tdfPDXAuthor.SetSourceTableName(_T("Author"));
dbsLocal.TableDefs.Append(tdfPDXAuthor);

dbsLocal.Close();


Container Property Example (VC++)

This example determines the name of the Container object to which a Document object belongs.

CString   strContainer;

strContainer = docUnknown.GetContainer();
if (strcmp(strContainer, _T("Tables")) == 0)
{
   //...
   return;
}
if (strcmp(strContainer, _T("Databases")) == 0)
{
   //...
   return;
}
if (strcmp(strContainer, _T("Forms")) == 0)
{
   //...
   return;
}
//...


Count Property Example (VC++)

This example lists the names and total number of TableDef and QueryDef objects in the current database.

CdbDBEngine      dbeng;
CdbDatabase      dbsLocal;
int               intCount, intMax;

dbsLocal = dbeng.OpenDatabase(_T("Northwind.mdb"));

// Print TableDef names and count.
intMax = dbsLocal.TableDefs.GetCount();
for (intCount=0; intCount < intMax; intCount++)
   printf(_T("  %s\n"),
      dbsLocal.TableDefs[intCount].GetName());
printf(_T("TableDef Count = %d\n\n"), intMax);

// Print QueryDef names and count.
intMax = dbsLocal.QueryDefs.GetCount();
for (intCount=0; intCount < intMax; intCount++)
   printf(_T("  %s\n"),
      dbsLocal.QueryDefs[intCount].GetName());
printf(_T("QueryDef Count = %d\n\n"), intMax);

dbsLocal.Close();


DateCreated and LastUpdated Properties Example (VC++)

This example determines the date and time when the Employees table was created and last updated.

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbRecordset      rstEmployees;
CDateTime      dtCreation, dtDesignChange;

dbsNorthwind = dbeng.Workspaces[0L].OpenDatabase(_T("Northwind.mdb"));
rstEmployees = dbsNorthwind.OpenRecordset(_T("Employees"));//open RS

dtCreation = rstEmployees.GetDateCreated();
dtDesignChange = rstEmployees.GetLastUpdated();

rstEmployees.Close();
dbsNorthwind.Close();


DesignMasterID Property Example (VC++)

This example uses the DesignMasterID property, ReplicaID property, and Synchronize method to move the DesignMaster to a replica.

/*   Notes:
   1)   Open current DesignMaster in exclusive mode.
      Cast the second operand as a BOOL to invoke the
      correct overloaded OpenDatabase method.
   2)   Open the database that will become the new
      DesignMaster.
   3) Synchronize will first copy the old
      DesignMaster's DesignMasterID to the replica.
      This will update the replica's DesignMasterID
      property to point to itself.
*/
void SetNewDesignMasterX(
                        LPCTSTR szOldDM,
                        LPCTSTR szNewDM )
{
   CdbDBEngine   dbeng;
   CdbDatabase   dbsOld, dbsNew;
                                    // note 1
   dbsOld = dbeng.OpenDatabase(szOldDM, (BOOL)TRUE);
   dbsNew = dbeng.OpenDatabase(szNewDM);   // note 2
   dbsOld.SetDesignMasterID(
                     (LPCTSTR)dbsNew.GetReplicaID());
   dbsOld.Synchronize(szNewDM,
                     dbRepImpExpChanges);// note 3
   dbsOld.Close();
   dbsNew.Close();
   return;
}


DistinctCount Property Example (VC++)

This example checks the DistinctCount property of an Index of a TableDef object opened on a table in the database.

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbTableDef      tdfCustomers;
CdbIndex      idxCurrent;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));
tdfCustomers = dbsNorthwind.TableDefs[_T("Customers")];
idxCurrent = tdfCustomers.Indexes[0L];

printf(_T("  DistinctCount: %s\n"), idxCurrent.GetDistinctCount());


EditMode Property Example (VC++)

This example checks the EditMode property of a Recordset object and completes the update if the AddNew method has been invoked or the object is being edited.

switch (rstTarget.GetEditMode())
{
   case dbEditAdd:
   case dbEditInProgress:
      rstTarget.Update;
      return -1;   //True
      break;

   default :
      return 0;   //False
      break;
}


Error Object, Errors Collection, and Description, Number, and Source Properties Example (VC++)

This example forces an error, traps it, and displays the Description, Number, and Source properties of the resulting Error object.

CdbDBEngine      dbeng;
CdbDatabase      db;

try
{
   db = dbeng.OpenDatabase(_T("DoesNotExist"));
}
catch (CdbException e)
{
   CdbError err;
   CString stErr, stErr2;

   for (int iErr = 0;
            iErr < dbeng.Errors.GetCount();
            iErr++)
   {
      err = dbeng.Errors[iErr];
      stErr.Format(_T("%ld"), DBERR(err.GetNumber()));
      stErr += _T(" : ");
      stErr2.Format(_T("%s"), err.GetDescription());
      stErr += stErr2 + _T(" : ");
      stErr2.Format(_T("%s"), err.GetSource());
      stErr += stErr2 + _T("\n");
   }
   MessageBox(NULL, stErr, _T("ForceError"), MB_OK);
}


Filter Property Example (VC++)

This example creates a dynaset-type Recordset that contains only records for orders shipped to the United Kingdom.

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbRecordset   rstOrders;
CdbRecordset   rstFiltered;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));

rstOrders = dbsNorthwind.OpenRecordset("Orders", dbOpenDynaset);
rstOrders.SetFilter(_T("ShipCountry = 'UK'"));
rstFiltered = rstOrders.OpenRecordset();

Note To change the contents of rstOrders, you must set its Filter property, and then open a second Recordset object based on rstOrders.

Note In some situations, it may be more efficient to create the second Recordset object with the conditions you want in one step. As a general rule, when you know the data you want to select, it's usually more efficient to create a Recordset with an SQL statement. This example shows how you can create just one Recordset and obtain the same results as in the preceding example:

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbRecordset      rstOrders;
CdbRecordset      rstFiltered;

dbsNorthwind =  dbeng. OpenDatabase(_T("Northwind.mdb"));
rstOrders = dbsNorthwind.OpenRecordset(_T("SELECT * FROM Orders WHERE ShipCountry = 'UK';"));


ForeignName, ForeignTable, and Table Properties Example (VC++)

This example shows how you can use the ForeignName, ForeignTable, and Table properties when you create a relationship between two existing tables — in this case, Table1 (the primary table) and Table2 (the foreign table) in the specified database. Field1 is the primary key in Table1 and Field2 is a foreign key in Table2. The relationship is one-to-many and referential integrity is enforced.

CdbDBEngine   dbeng;
CdbDatabase   dbsDefault;
CdbField   fldLocal;
CdbRelation   relForeign;

// Get database
dbsDefault =  dbeng.OpenDatabase(_T("Northwind.mdb"));

// Create new relationship and set its properties.
relForeign = dbsDefault.CreateRelation(_T("MyRelation"));
relForeign.SetTable(_T("Table1"));
relForeign.SetForeignTable(_T("Table2"));

// Create field and set its properties.
fldLocal = relForeign.CreateField(_T("Field1"));
fldLocal.SetForeignName(_T("Field2"));

// Append field to relation and relation to database.
relForeign.Fields.Append(fldLocal);
dbsDefault.Relations.Append(relForeign);
dbsDefault.Close();


HelpContext and HelpFile Properties Example (VC++)

This example displays the HelpContext and HelpFile properties of an Error object. The HelpFile property contains the name of the Microsoft Jet database engine error message Help file.

CdbDBEngine   dbeng;
//
try
{
   throw (E_DAO_DatabaseInvalidName);   //error 3005
}
catch (CdbException)
{
   CdbError err = dbeng.Errors[0L];
   CString stMsg, stTitle;
   //
   stTitle =
      err.GetDescription() +
      stMsg.Format(_T("%ld"), err.GetHelpContext()) +
      err.GetHelpFile();
   stMsg =    "Press F1 or Help to see " +
            err.GetHelpFile() +
            " topic for this error";
   MessageBox(
      NULL, stMsg, _T("Error: " + stTitle), MB_OK);
}


Index and Unique Properties Example (VC++)

This example adds a new index to a TableDef object in the Biblio.mdb database, makes that index the current index, and invokes the Seek method based on that index. The names of the Field objects created and appended to the Fields collection of the Index object correspond to the names of current fields in the table.

CdbDBEngine         dbeng;
CdbRecordset      rstPublishers;
CdbDatabase         dbsBiblio;
CdbIndex         idxPubIDName;
CdbField         fldPubID;
CdbField         fldName;
COleVariant         vYourdon(_T("Yourdon Press"));

dbsBiblio = dbeng.OpenDatabase(_T("Biblio.mdb"));
idxPubIDName =    dbsBiblio.TableDefs[_T("Publishers")].CreateIndex(
      _T("PubID Name"));
fldPubID = idxPubIDName.CreateField(_T("PubID"));
idxPubIDName.Fields.Append(fldPubID);
fldName = idxPubIDName.CreateField(_T("Name"));
idxPubIDName.Fields.Append(fldName);
idxPubIDName.SetUnique(-1);  //True

// Append the new Index to the Indexes collection.
dbsBiblio.TableDefs[_T("Publishers")].Indexes.Append(
   idxPubIDName);

//Open the table, look for publisher.
rstPublishers =
 dbsBiblio.OpenRecordset(_T("Publishers"),dbOpenTable);
rstPublishers.SetIndex(_T("PubID Name"));
rstPublishers.Seek(_T("="), 1, vYourdon);
if (rstPublishers.GetNoMatch())
{
   rstPublishers.MoveFirst();
   printf(_T("Not found\n"));
}
else {
   printf(_T("Name: %s\n"), rstPublishers.GetName());
}

rstPublishers.Close();

This example sets the index for rstOrders to the primary key. (PrimaryKey is the default name of an Index object if the primary key is set in the table's Design view.) Next, it locates the record with a matching key field value of 10,050. Notice that the current index must be set before certain operations, such as the Seek method, can be performed.

CdbDBEngine         dbeng;
CdbDatabase         dbsNorthwind;
CdbRecordset      rstOrders;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));
rstOrders = dbsNorthwind.OpenRecordset(   _T("Orders"),
                                    dbOpenTable);
                           // Set current index.
rstOrders.SetIndex(_T("PrimaryKey"));
                           // Locate record.
rstOrders.Seek(_T("="), 1, COleVariant(10500, VT_I4));
rstOrders.Close();               // Close recordset.
dbsNorthwind.Close();            // Close database.


Inherit Property Example (VC++)

This example sets the table container’s Inherit property to True, and then sets the Permissions property to allow users to alter the security settings of documents.

CdbDBEngine   dbeng;
CdbDatabase   dbsNorthwind;
CdbContainer   conTables;

dbsNorthwind =  dbeng.Workspaces[0L].OpenDatabase(_T("Northwind.mdb"));
conTables = dbsNorthwind.Containers[_T("Tables")];
conTables.SetInherit(-1);   //True
conTables.SetPermissions(dbSecWriteSec);
dbsNorthwind.Close();


Inherited Property Example (VC++)

This example creates a Recordset object from a QueryDef object, creates a new property, and indicates whether the property is inherited. Then the example prints the name of each field in the Recordset and, for each property of each field, it prints the Name, Type, Value, and Inherited property value settings.

CdbDBEngine      dbeng;
CdbDatabase      dbsDefault;
CdbQueryDef      qdfTest;
CdbRecordset   rstTest;
CdbProperty      prp;
CdbField      fld;
COleVariant      vVal;
int             intField, intFieldMax,
            intProp, intPropMax;
//
dbsDefault = dbeng.OpenDatabase(_T("Northwind.mdb"));
qdfTest = dbsDefault.QueryDefs[0L];
prp =
   qdfTest.CreateProperty(
      _T("Moose"),dbBoolean, TRUE);
qdfTest.Properties.Append(prp);
rstTest = qdfTest.OpenRecordset();

printf(_T("Is rstTest.Properties(\"Moose\")inherited? %i\n"),
   qdfTest.Properties[_T("Moose")].GetInherited());
printf(_T("Is rstTest.Properties(\"Moose\")inherited? %i\n"),          rstTest.Properties[_T("Moose")].GetInherited());

intFieldsMax = rstTest.Fields.GetCount();
for (intField = 0; intField < intFieldsMax; intField++)
{
   fld = rstTest.Fields[intField];
   printf(_T(fld.GetName()));

   //On Error Resume Next
   intPropMax = fld.Properties.GetCount();
   for (   intProp = 0;
         intProp < intPropMax;
         intProp++)
   {
   try {   // Ignore write-only properties.
      prp = fld.Properties[intProp];
      printf(_T(prp.GetName()));
      printf(" %i", prp.GetType());
      vVal = prp.GetValue();
      vVal.ChangeType(VT_BSTR);
      printf(" %S", vVal.bstrVal);
      printf(" %i\n", prp.GetInherited());
      }
   catch (CdbException)
      {}
   }

}


IniPath Property Example (VC++)

This example sets the path in the IniPath property to an application’s key in the Windows Registry.

CdbDBEngine   dbeng;
LPCTSTR      pstr;

pstr ="HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MyApp\\3.0\\KeyFolder";
dbeng.SetIniPath(pstr);


IsolateODBCTrans Property Example (VC++)

This example opens a Workspace and sets IsolateODBCTrans to True before starting a transaction.

CdbDBEngine   DBEng;
CdbWorkspace   wrkDefault;

wrkDefault = DBEng.Workspaces[0L];
wrkDefault.SetIsolateODBCTrans(-1);
wrkDefault.BeginTrans();
// Execute query to ODBC database and complete transaction.


LockEdits Property Example (VC++)

This example opens a dynaset-type Recordset and sets its LockEdits property to False. This enables optimistic locking so other users can change the database records at any time. Your application triggers a trappable error if the data changes before you use the Update method.

CdbDBEngine      DBEng;
CdbDatabase      dbsNorthwind;
CdbRecordset   rstCustomers;

dbsNorthwind = DBEng.OpenDatabase(_T("Northwind.mdb"));
rstCustomers = dbsNorthwind.OpenRecordset(_T("Customers"),
                     dbOpenDynaset);
rstCustomers.SetLockEdits(-1);
try
{
   rstCustomers.Edit();
}
catch (CdbException e)
{
   if (DBEng.Errors[0L].GetNumber() == 3197)
      printf(_T("data changed\n"));
   else
      printf(_T("some other error\n"));
}

rstCustomers.CancelUpdate();
rstCustomers.Close();
dbsNorthwind.Close();


LoginTimeout Property Example (VC++)

This example sets the LoginTimeout property to 120 seconds and then creates and runs a query on a database on an ODBC server.

CdbDBEngine   DBEng;
CdbDatabase   dbsNorthwind;
CdbQueryDef   qdfCustomers;
CdbRecordset   rstCustomers;

DBEng.SetLoginTimeout(120);      // Timeout in 2 minutes.
dbsNorthwind =  DBEng. OpenDatabase(_T("Northwind.mdb"));
                           // Create query.
qdfCustomers = dbsNorthwind.CreateQueryDef(_T("All Cust"),
_T("SELECT * FROM Customers;"));
qdfCustomers.SetConnect(_T("ODBC;DSN=Human Resources;DATABASE=HRSRVR; UID=Smith; PWD=Sesame"));
                           // Log in to server and run query.
rstCustomers = qdfCustomers.OpenRecordset();


Name Property Example (VC++)

This example creates a TableDef object and then names it Parts ID.

CdbDBEngine   DBEng;
CdbDatabase   dbsNorthwind;
CdbQueryDef   qdfCustomers;
CdbRecordset   rstCustomers;
CdbTableDef   tdfPartsID;

dbsNorthwind =  DBEng.OpenDatabase(_T("Northwind.mdb"));
tdfPartsID = dbsNorthwind.CreateTableDef();
tdfPartsID.SetName(_T("Parts ID"));
//...   ' Create fields.
dbsNorthwind.TableDefs.Append(tdfPartsID);


NoMatch Property Example (VC++)

This example changes the job title of all sales representatives in an Employees table. It creates a dynaset-type Recordset and then uses FindFirst and FindNext to locate every record satisfying the criteria for the title. It prepares each record for editing, changes the title, and saves the change with the Update method.

Cstring      strCriteria;
CdbBookmark   varSaveHere;

CdbDBEngine   DBEng;
CdbDatabase   dbsNorthwind;
CdbRecordset   rstEmployees;

strCriteria = (_T("Title = 'Sales Representative'"));
dbsNorthwind =  DBEng.OpenDatabase(_T("Northwind.mdb"));
rstEmployees = dbsNorthwind.OpenRecordset(_T("Employees"), dbOpenDynaset);
varSaveHere = rstEmployees.GetBookmark(); //   ' Save Bookmark.

rstEmployees.FindFirst(strCriteria); //   ' Locate first occurrence.
while (! rstEmployees.GetNoMatch())
   {
   rstEmployees.Edit();            //   ' Enable editing.
   rstEmployees.SetField(_T("Title"),
COleVariant(_T("Account Executive"));
   rstEmployees.Update();         //   ' Save changes.
   rstEmployees.FindNext(strCriteria);   //   ' Locate next record.
   }
rstEmployees.SetBookmark(&varSaveHere);

Note In some situations, using an update query is faster.


ODBCTimeoutProperty Example (VC++)

This example sets the ODBCTimeout property to 120 seconds and then creates a query and runs it on a database on an ODBC server.

Cstring      strCriteria;
CdbBookmark   varSaveHere;

CdbDBEngine   DBEng;
CdbDatabase   dbsNorthwind;
CdbRecordset   rstCustomers;
CdbQueryDef   qdfCustomers;

dbsNorthwind = DBEng.OpenDatabase(_T("Northwind.mdb"));
// Create query.
qdfCustomers = dbsNorthwind.CreateQueryDef(_T("All Cust"), _T("SELECT * FROM Customers;"));
qdfCustomers.SetConnect(_T("ODBC;DSN=Human Resources; SERVER=HRSRVR; UID=Smith; PWD=Sesame"));
// Log in to server and run query.
qdfCustomers.SetODBCTimeout(120);
rstCustomers = qdfCustomers.OpenRecordset();


Owner Property Example (VC++)

This example changes the Owner property setting of a Document object after determining whether the current user has the appropriate permissions to do so.

CdbDBEngine   DBEng;
CdbDatabase   dbsNorthwind;
CdbDocument   docTest;

dbsNorthwind =  DBEng.OpenDatabase(_T("Northwind.mdb"));
docTest = dbsNorthwind.Containers[0L].Documents[0L];
if ((docTest.GetPermissions() & dbSecWriteOwner) != 0)       docTest.SetOwner(_T("SomebodyElse"));


Password and PID Properties Example (VC++)

This example creates a new User object and sets the Name, PID, and Password properties for the new object before appending it to the Users collection.

Cstring      strCriteria;
CdbBookmark   varSaveHere;

CdbDBEngine   DBEng;
CdbUser      usrMyself;
CdbWorkspace   wrkDefault;

//...
wrkDefault = DBEng.Workspaces[0L];  // ' Get default workspace.
// Create, specify, and append new User object.
usrMyself = wrkDefault.CreateUser(_T("Pat Smith"));
usrMyself.SetPID(_T("abc123DEF456"));
usrMyself.SetPassword(_T("MySecret"));
wrkDefault.Users.Append(usrMyself);


PercentPosition Property Example (VC++)

This example displays the current position of a record in a Recordset in a message box.

CdbDBEngine   DBEng;
CdbDatabase   dbsNorthwind;
CdbRecordset   rstEmployees;
Cstring   stPrctPos;

dbsNorthwind =  DBEng.OpenDatabase(_T("Northwind.mdb"));
// Open table.
rstEmployees = dbsNorthwind.OpenRecordset(_T("Employees"));
// Set current index.
rstEmployees.SetIndex(_T("Last Name"));
//...
//...   ' Move among the records.
//...
//' Display current position.
stPrctPos.Format(_T("%f"), rstEmployees.GetPercentPosition());
printf(_T("Current position is %s%%."), stPrctPos);


Permissions Property Example (VC++)

This example prints the Permissions property setting of a Document object for the current user.

CdbDBEngine   DBEng;
CdbDatabase   dbsNorthwind;
CdbDocument   docTest;
Cstring      stPermission;

dbsNorthwind =  DBEng.OpenDatabase(_T("Northwind.mdb"));
docTest = dbsNorthwind.Containers[0L].Documents[_T("MyDoc")];
stPermission.Format(_T("%f"),docTest.GetPermissions());
printf ("%s\n", stPermission);


Primary Property Example (VC++)

In the Biblio.mdb database, this example creates a new Table and primary key Index object and then adds the Table to the TableDefs collection of a Database.

CdbDBEngine      dbeng;
CdbDatabase      dbsBiblio;
CdbIndex      idxPrimaryKey;
CdbField      fldTypeNum, fldType;
CdbTableDef      tdfBookTypes;

//Open the Database.
dbsBiblio = dbeng.OpenDatabase(__T("Northwind.mdb"));
tdfBookTypes = dbsBiblio.CreateTableDef(_T("Book Types"));

// Create and Set fldTypeNum field
fldTypeNum = tdfBookTypes.CreateField(_T("TypeNum"), dbLong);
// Add fldTypeNum field to TableDef.
tdfBookTypes.Fields.Append(fldTypeNum);

// Create and Set fldType field properties.
fldType = tdfBookTypes.CreateField(_T("Type"),dbText);

// Set Size property of text field.
fldType.SetSize(15);

// Add fldType field to TableDef.
tdfBookTypes.Fields.Append(fldType);

// Set properties in new Index.
idxPrimaryKey = tdfBookTypes.CreateIndex(_T("PrimaryKey"));
idxPrimaryKey.SetName(_T("PrimaryKey"));
idxPrimaryKey.SetUnique(TRUE);
idxPrimaryKey.SetPrimary(TRUE);

// put the TypeNum field in this index
idxPrimaryKey.Fields.Append((CdbField)idxPrimaryKey.CreateField(
_T("TypeNum")));

// Add Index to TableDefs collection.
tdfBookTypes.Indexes.Append(idxPrimaryKey);

//   Append TableDef to database.
dbsBiblio.TableDefs.Append(tdfBookTypes);
dbsBiblio.Close();


QueryTimeout Property Example (VC++)

This example opens the specified database and sets the QueryTimeout property to 120 seconds.

CdbDBEngine   dbeng;
CdbDatabase   dbsNorthwind;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));
dbsNorthwind.SetQueryTimeout(120);
dbsNorthwind.Close();


RecordCount Property Example (VC++)

This example creates a Recordset object based on the Employees table and then determines the number of records in the Recordset.

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbRecordset   rstEmployees;
long            lTotal;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));
rstEmployees = dbsNorthwind.OpenRecordset(_T("Employees"));
rstEmployees.MoveLast();
lTotal = rstEmployees.GetRecordCount();

if (lTotal == -1)
   printf(_T("Count not available\n"));

dbsNorthwind.Close();


RecordsAffected Property Example (VC++)

This example prints the number of records updated by an action query.

CdbDBEngine      dbeng;
CdbDatabase      dbsBiblio;
long            lTotal;

dbsBiblio = dbeng.OpenDatabase(_T("Biblio.mdb"));
dbsBiblio.Execute(_T("Update Titles Set [Year Published] = 1994
Where Title = 'To Kill an SQL Query'"));
lTotal = dbsBiblio.GetRecordsAffected();
printf("%d records were changed.", lTotal);
dbsBiblio.Close();


Restartable Property and Requery Method Example (VC++)

This example determines the Restartable property setting of a dynaset-type Recordset and then uses the Requery method on the Recordset.

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbRecordset   rstChangeOften;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));

rstChangeOften = dbsNorthwind.OpenRecordset(_T("Table That Changes
Often"),dbOpenDynaset);
if (rstChangeOften.GetRestartable())
   rstChangeOften.Requery();
dbsNorthwind.Close();


ReturnsRecords Property Example (VC++)

The following example creates an SQL pass-through query that returns records from an external database.

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbQueryDef      qdfPassThrough;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));

qdfPassThrough = dbsNorthwind.CreateQueryDef(_T("October Orders"),
      _T("SELECT * From Orders WHERE ShipCity = 'London'"));
qdfPassThrough.SetConnect(_T("ODBC;
DSN=MySQLDBDSN;UID=Chrissy;PWD=FourOh;"));
qdfPassThrough.SetReturnsRecords(TRUE);
dbsNorthwind.Close();


Size and Type Properties Example (VC++)

This example creates a new Field object with a Text field type, sets its Name property to Fax Phone and its Size property to 20, and appends the new object to the Fields collection of the Employees table in the TableDefs collection of the database.

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbTableDef      tdfEmployees;
CdbField         fldFaxPhone;

// open database
dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));
// get existing table reference
tdfEmployees = dbsNorthwind.TableDefs.Item(_T("Employees"));
// create field object
fldFaxPhone = tdfEmployees.CreateField(_T("Fax Phone"));
// set field properties
fldFaxPhone.SetType(dbText);
fldFaxPhone.SetSize(20);
// append fldFaxPhone to Fields collection
tdfEmployees.Fields.Append(fldFaxPhone);
return TRUE;

You can also use the CreateField method if you provide name, type, and size as arguments.

FldFaxPhone = tdfEmployees.CreateField(_T("Fax Phone"), dbText, 20);


Sort Property Example (VC++)

This example uses the Sort property to set the sort order of a dynaset-type Recordset based on an Orders table. The records in rstSorted will be in ascending Ship Country order.

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbRecordset   rstOrders;
CdbRecordset   rstSorted;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));
rstOrders = dbsNorthwind.OpenRecordset(_T("Orders"), dbOpenDynaset);
// set sort order
rstOrders.SetSort(_T("ShipCountry"));
// create 2nd recordset
rstSorted = rstOrders.OpenRecordset();

// process...

rstSorted.Close();
rstOrders.Close();
dbsNorthwind.Close();

Note In some situations, it may be more efficient to create the second Recordset object with the conditions you want in one step. As a general rule, when you know the data you want to select, it's usually more efficient to create a Recordset with an SQL statement. This example shows how you can create just one Recordset and obtain the same results as in the preceding example.

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbRecordset      rstOrders;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));
rstOrders = dbsNorthwind.OpenRecordset(_T("SELECT * FROM Orders   ORDER BY ShipCountry;"));
// process...

rstOrders.Close();
dbsNorthwind.Close();


SourceField and SourceTable Properties Example (VC++)

This example creates a Recordset object using an SQL statement that creates aliases for fields in two different tables in the database. The example then prints the name of the field, the original table, and the original field.

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbRecordset      rstEmployCustID;
CdbField         fldEnum;
int            i;

// open database
dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));

rstEmployCustID = dbsNorthwind.OpenRecordset(_T("SELECT   EmployeeID
   as EmpID, CustormerID as CustID FROM Employees, Customers;"));

for (i=0;i<rstEmployCustID.Fields.GetCount();i++)
   {
   fldEnum = rstEmployCustID.Fields.Item(i);
   // print field name
   printf("%s",fldEnum.GetName());
   // print original table name
   printf("%s",fldEnum.GetSourceTable());
   // print original field name
   printf("%s", fldEnum.GetSourceField());
   }

rstEmployCustID.Close();
dbsNorthwind.Close();


SQL Property Example (VC++)

This example creates a query based on an Orders table. The query selects all orders that have a Freight value greater than 10.

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbQueryDef      qdfLargeFrt;
CdbRecordset   rstFromQuery;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));
qdfLargeFrt = dbsNorthwind.CreateQueryDef(_T("Large Freight"));
qdfLargeFrt.SetSQL( _T("SELECT * FROM Orders WHERE Freight >
10;"));
rstFromQuery = qdfLargeFrt.OpenRecordset(dbOpenSnapshot);
// process
rstFromQuery.Close();
dbsNorthwind.Close();


Updatable Property Example (VC++)

This example adds a record to a Recordset object if the object's Updatable property setting is True.

CdbDBEngine      dbeng;
CdbDatabase      dbsNorthwind;
CdbRecordset   rstUnknown;

dbsNorthwind = dbeng.OpenDatabase(_T("Northwind.mdb"));
rstUnknown =
   dbsNorthwind.OpenRecordset(_T("Unfamiliar Table"));
if (rstUnknown.GetUpdatable())
{
   rstUnknown.AddNew();
   rstUnknown.SetField(_T("MyField"),
               &COleVariant(_T("Some new data")));
   rstUnknown.Update();
}
dbsNorthwind.Close;


UserName Property Example (VC++)

This example sets the access permissions for a table named MyTable in the specified database for a user named Millicent to read-only. The code then checks to see if Millicent has permission to add records.

CdbDBEngine      dbeng;
CdbWorkspace   wrkDefault;
CdbDatabase      dbsNorthwind;
CdbDocument      docMyTable;

wrkDefault = dbeng.Workspaces[0L];
dbsNorthwind = wrkDefault.OpenDatabase(_T("Northwind.mdb"));

docMyTable = dbsNorthwind.Containers[_T("Tables")][_T("MyTable")];
docMyTable.SetUserName(_T("Millicent"));
docMyTable.SetPermissions(dbSecRetrieveData);
if (docMyTable.GetPermissions() & dbSecInsertData)
  printf(_T("Millicent can insert data"));
else
 printf(_T("Millicent can't insert data"));
...


Version Property Example (VC++)

This example checks the version number of the Microsoft Jet database engine and splits it into the version number and release number. The example doesn't check for an invalid string.

CdbDBEngine      dbeng;
CString         strJetRelease;

strJetRelease = dbeng.GetVersion();
...


Comparison of Microsoft Jet Database Engine SQL and ANSI SQL

Microsoft Jet database engine SQL is generally ANSI-89 Level 1 compliant. However, certain ANSI SQL features aren't implemented in Microsoft Jet SQL. Conversely, Microsoft Jet SQL includes reserved words and features not supported in ANSI SQL.


Major Differences

  • Microsoft Jet SQL and ANSI SQL each have different reserved words and data types. For more information, see Microsoft Jet Database Engine SQL Reserved Words and Equivalent ANSI SQL Data Types.

  • Different rules apply to the Between...And construct, which has the following syntax:

    expr1 [NOT] Between value1 And value2

    In Microsoft Jet SQL, value1 can be greater than value2; in ANSI SQL, value1 must be equal to or less than value2.

  • Different wildcard characters are used with the Like operator.
Matching character | Microsoft Jet SQL | ANSI SQL
Any single character | ? | _ (underscore)
Zero or more characters | * | %

  • Microsoft Jet SQL is generally less restrictive. For example, it permits grouping and ordering on expressions.

  • Microsoft Jet SQL supports more powerful expressions.


Enhanced Features of Microsoft Jet SQL

Microsoft Jet SQL provides the following enhanced features:

  • The TRANSFORM statement, which provides support for crosstab queries

  • Additional aggregate functions, such as StDev and VarP

  • The PARAMETERS declaration for defining parameter queries


ANSI SQL Features Not Supported in Microsoft Jet SQL

Microsoft Jet SQL doesn't support the following ANSI SQL features:

  • Security statements, such as COMMIT, GRANT, and LOCK.

  • DISTINCT aggregate function references. For example, Microsoft Jet SQL doesn't allow SUM(DISTINCT columnname).

  • The LIMIT TO nn ROWS clause used to limit the number of rows returned by a query. You can use only the WHERE clause to limit the scope of a query.


Equivalent ANSI SQL Data Types

The following table lists ANSI SQL data types and the equivalent Microsoft Jet database engine SQL data types and their valid synonyms.

ANSI SQL data type | Microsoft Jet SQL data type | Synonym
BIT, BIT VARYING | BINARY (See Notes) | VARBINARY
Not supported | BIT (See Notes) | BOOLEAN, LOGICAL, LOGICAL1, YESNO
Not supported | BYTE | INTEGER1
Not supported | COUNTER | AUTOINCREMENT
Not supported | CURRENCY | MONEY
DATE, TIME, TIMESTAMP | DATETIME | DATE, TIME, TIMESTAMP
Not supported | GUID |
DECIMAL | Not supported |
REAL | SINGLE | FLOAT4, IEEESINGLE, REAL
DOUBLE PRECISION, FLOAT | DOUBLE | FLOAT, FLOAT8, IEEEDOUBLE, NUMBER, NUMERIC
SMALLINT | SHORT | INTEGER2, SMALLINT
INTEGER | LONG | INT, INTEGER, INTEGER4
INTERVAL | Not supported |
Not supported | LONGBINARY | GENERAL, OLEOBJECT
Not supported | LONGTEXT | LONGCHAR, MEMO, NOTE
CHARACTER, CHARACTER VARYING | TEXT | ALPHANUMERIC, CHAR, CHARACTER, STRING, VARCHAR
Not supported | VALUE (See Notes) |

Notes

  • The ANSI SQL BIT data type doesn't correspond to the Microsoft Jet SQL BIT data type, but it corresponds to the BINARY data type instead. There is no ANSI SQL equivalent for the Microsoft Jet SQL BIT data type.

  • The VALUE reserved word doesn't represent a data type defined by the Microsoft Jet database engine.


Microsoft Jet Database Engine SQL Data Types

The Microsoft Jet database engine SQL data types consist of 13 primary data types defined by the Microsoft Jet database engine and several valid synonyms recognized for these data types.

The following table lists the primary data types. The synonyms are identified in Microsoft Jet Database Engine SQL Reserved Words.

Data type | Storage size | Description
BINARY | 1 byte per character | Any type of data may be stored in a field of this type. No translation of the data (for example, to text) is made. How the data is input in a binary field dictates how it will appear as output.
BIT | 1 byte | Yes and No values and fields that contain only one of two values.
BYTE | 1 byte | An integer value between 0 and 255.
COUNTER | 4 bytes | A number automatically incremented by the Microsoft Jet database engine whenever a new record is added to a table. In the Microsoft Jet database engine, the data type for this value is Long.
CURRENCY | 8 bytes | A scaled integer between – 922,337,203,685,477.5808 and 922,337,203,685,477.5807.
DATETIME (See DOUBLE) | 8 bytes | A date or time value between the years 100 and 9999.
GUID | 128 bits | A unique identification number used with remote procedure calls.
SINGLE | 4 bytes | A single-precision floating-point value with a range of – 3.402823E38 to – 1.401298E-45 for negative values, 1.401298E-45 to 3.402823E38 for positive values, and 0.
DOUBLE | 8 bytes | A double-precision floating-point value with a range of – 1.79769313486232E308 to – 4.94065645841247E-324 for negative values, 4.94065645841247E-324 to 1.79769313486232E308 for positive values, and 0.
SHORT | 2 bytes | A short integer between – 32,768 and 32,767.
LONG | 4 bytes | A long integer between – 2,147,483,648 and 2,147,483,647.
LONGTEXT | 1 byte per character | Zero to a maximum of 1.2 gigabytes.
LONGBINARY | As required | Zero to a maximum of 1.2 gigabytes. Used for OLE objects.
TEXT | 1 byte per character | Zero to 255 characters.

Note You can also use the VALUE reserved word in SQL statements.


SQL Expressions

An SQL expression is a string that makes up all or part of an SQL statement. For example, the FindFirst method on a Recordset object uses an SQL expression consisting of the selection criteria found in an SQL WHERE clause.

The Microsoft Jet database engine uses the Visual Basic for Applications (or VBA) expression service to perform simple arithmetic and function evaluation. All of the operators used in Microsoft Jet SQL expressions (except Between, In, and Like) are defined by the VBA expression service. In addition, the VBA expression service offers over 100 VBA functions that you can use in SQL expressions. For example, you can use these VBA functions to compose an SQL query in the Microsoft Access query Design view, and you can also use these functions in an SQL query in the DAO OpenRecordset method in Microsoft Visual C++, Microsoft Visual Basic, and Microsoft Excel code.


Between...And Operator (Microsoft Jet SQL)

Between...And Operator

Determines whether the value of an expression falls within a specified range of values. You can use this operator within SQL statements.

Syntax

expr [Not] Between value1 And value2

The Between...And operator syntax has these parts:

Part | Description
expr | Expression identifying the field that contains the data you want to evaluate.
value1, value2 | Expressions against which you want to evaluate expr.

Remarks

If the value of expr is between value1 and value2 (inclusive), the Between...And operator returns True; otherwise, it returns False. You can include the Not logical operator to evaluate the opposite condition (that is, whether expr lies outside the range defined by value1 and value2).

You might use Between...And to determine whether the value of a field falls within a specified numeric range. The following example determines whether an order was shipped to a location within a range of postal codes. If the postal code is between 98101 and 98199, the IIf function returns "Local". Otherwise, it returns "Nonlocal".

SELECT IIf(PostalCode Between 98101 And 98199, "Local", "Nonlocal")
FROM Publishers

If expr, value1, or value2 is Null, Between...And returns a Null value.

Because wildcard characters, such as *, are treated as literals, you cannot use them with the Between...And operator. For example, you cannot use 980* and 989* to find all postal codes that start with 980 to 989. Instead, you have two alternatives for accomplishing this. You can add an expression to the query that takes the left three characters of the text field and use Between...And on those characters. Or you can pad the high and low values with extra characters — in this case, 98000 to 98999, or 98000 to 98999 – 9999 if using extended postal codes. (You must omit the – 0000 from the low values because otherwise 98000 is dropped if some postal codes have extended sections and others do not.)


In Operator (Microsoft Jet SQL)

In Operator

Determines whether the value of an expression is equal to any of several values in a specified list.

Syntax

expr [Not] In(value1, value2, . . .)

Remarks

The In operator syntax has these parts:

Part | Description
expr | Expression identifying the field that contains the data you want to evaluate.
value1, value2 | Expression or list of expressions against which you want to evaluate expr.

If expr is found in the list of values, the In operator returns True; otherwise, it returns False. You can include the Not logical operator to evaluate the opposite condition (that is, whether expr is not in the list of values).

For example, you can use In to determine which orders are shipped to a set of specified regions:

SELECT *
FROM Orders
WHERE ShipRegion In ('Avon','Glos','Som')


Like Operator (Microsoft Jet SQL)

Like Operator

Compares a string expression to a pattern in an SQL expression.

Syntax

expression Like "pattern"

The Like operator syntax has these parts:

Part | Description
expression | SQL expression used in a WHERE clause.
pattern | String or character string literal against which expression is compared.

Remarks

You can use the Like operator to find values in a field that match the pattern you specify. For pattern, you can specify the complete value (for example, Like "Smith"), or you can use wildcard characters to find a range of values (for example, Like "Sm*").

In an expression, you can use the Like operator to compare a field value to a string expression. For example, if you enter Like "C*" in an SQL query, the query returns all field values beginning with the letter C. In a parameter query, you can prompt the user for a pattern to search for.

The following example returns data that begins with the letter P followed by any letter between A and F and three digits:

Like "P[A-F]###"

The following table shows how you can use Like to test expressions for different patterns.

Kind of match | Pattern | Match (returns True) | No match (returns False)
Multiple characters | a*a | aa, aBa, aBBBa | aBC
 | *ab* | abc, AABB, Xab | aZb, bac
Special character | a[*]a | a*a | aaa
Multiple characters | ab* | abcdefg, abc | cab, aab
Single character | a?a | aaa, a3a, aBa | aBBBa
Single digit | a#a | a0a, a1a, a2a | aaa, a10a
Range of characters | [a-z] | f, p, j | 2, &
Outside a range | [!a-z] | 9, &, % | b, a
Not a digit | [!0-9] | A, a, &, ~ | 0, 1, 9
Combined | a[!b-m]# | An9, az0, a99 | abc, aj0


Using Wildcard Characters in String Comparisons

Built-in pattern matching provides a versatile tool for making string comparisons. The following table shows the wildcard characters you can use with the Like operator and the number of digits or strings they match.

Character(s) in pattern | Matches in expression
? | Any single character
* | Zero or more characters
# | Any single digit (0 — 9)
[charlist] | Any single character in charlist
[!charlist] | Any single character not in charlist

You can use a group of one or more characters (charlist) enclosed in brackets ([ ]) to match any single character in expression, and charlist can include almost any characters in the ANSI character set, including digits. In fact, you can use the special characters opening bracket ([ ), question mark (?), number sign (#), and asterisk (*) to match themselves directly only if enclosed in brackets. You can't use the closing bracket ( ]) within a group to match itself, but you can use it outside a group as an individual character.

In addition to a simple list of characters enclosed in brackets, charlist can specify a range of characters by using a hyphen (-) to separate the upper and lower bounds of the range. For example, using [A-Z] in pattern results in a match if the corresponding character position in expression contains any of the uppercase letters in the range A through Z. You can include multiple ranges within the brackets without delimiting the ranges. For example, [a-zA-Z0-9] matches any alphanumeric character.

Other important rules for pattern matching include the following:

  • An exclamation mark (!) at the beginning of charlist means that a match is made if any character except those in charlist are found in expression. When used outside brackets, the exclamation mark matches itself.

  • You can use the hyphen (-) either at the beginning (after an exclamation mark if one is used) or at the end of charlist to match itself. In any other location, the hyphen identifies a range of ANSI characters.

  • When you specify a range of characters, the characters must appear in ascending sort order (A-Z or 0-100). [A-Z] is a valid pattern, but [Z-A] isn't.

  • The character sequence [ ] is ignored; it's considered to be a zero-length string ("").


Microsoft Jet Database Engine SQL Reserved Words

{button A, JI(daidxSqlA)} {button B, JI(daidxSqlB_C)} {button C, JI(daidxSqlB_C)} {button D, JI(daidxSqlD)} {button E, JI(daidxSqlE_H)} {button F, JI(daidxSqlE_H)} {button G, JI(daidxSqlE_H)} {button H, JI(daidxSqlE_H)} {button I, JI(daidxSqlI)} {button J, JI(daidxSqlJ_M)} {button K, JI(daidxSqlJ_M)} {button L, JI(daidxSqlJ_M)} {button M, JI(daidxSqlJ_M)} {button N, JI(daidxSqlN_P)} {button O, JI(daidxSqlN_P)} {button P, JI(daidxSqlN_P)} {button Q, JI(daidxSqlQ_S)} {button R, JI(daidxSqlQ_S)} {button S, JI(daidxSqlQ_S)} {button T, JI(daidxSqlT_Z)} {button U, JI(daidxSqlT_Z)} {button V, JI(daidxSqlT_Z)} {button W, JI(daidxSqlT_Z)} {button X, JI(daidxSqlT_Z)} {button Y, JI(daidxSqlT_Z)} {button Z, JI(daidxSqlT_Z)}

The following list includes all words reserved by the Microsoft Jet database engine for use in SQL statements. The words in the list that aren't in all uppercase letters are also reserved by other applications. Consequently, the individual Help topics for these words provide general descriptions that don't focus on SQL usage.

Note Words followed by an asterisk (*) are reserved but currently have no meaning in the context of a Microsoft Jet SQL statement (for example, Level and TableID).


(Untitled)

A

ADD

ALL

Alphanumeric — See TEXT

ALTER

And

ANY

AS

ASC

AUTOINCREMENT — See COUNTER

Avg


(Untitled)

B-C

Between

BINARY

BIT

BOOLEAN — See BIT

BY

BYTE

CHAR, CHARACTER — See TEXT

 COLUMN

CONSTRAINT

Count

COUNTER

CREATE

CURRENCY


(Untitled)

D

DATABASE

DATE — See DATETIME

DATETIME

DELETE

DESC

 DISALLOW

DISTINCT

DISTINCTROW

DOUBLE

DROP


(Untitled)

E-H

Eqv

EXISTS

FLOAT, FLOAT8 — See DOUBLE

FLOAT4 — See SINGLE

FOREIGN

 FROM

GENERAL — See LONGBINARY

GROUP

GUID

HAVING


(Untitled)

I

IEEEDOUBLE — See DOUBLE

IEEESINGLE — See SINGLE

IGNORE

Imp

In

IN

INDEX

 INNER

INSERT

INT, INTEGER, INTEGER4 — See LONG

INTEGER1 — See BYTE

INTEGER2 — See SHORT

INTO

Is


(Untitled)

J-M

JOIN

KEY

LEFT

Level*

Like

LOGICAL, LOGICAL1 — See BIT

LONG

LONGBINARY

LONGTEXT

Max

MEMO — See LONGTEXT

Min

Mod

MONEY — See CURRENCY


(Untitled)

N-P

Not

NULL

NUMBER — See DOUBLE

NUMERIC — See DOUBLE

OLEOBJECT — See LONGBINARY

On

OPTION

Or

ORDER

Outer*

OWNERACCESS

PARAMETERS

PERCENT

PIVOT

PRIMARY

PROCEDURE


(Untitled)

Q-S

REAL — See SINGLE

REFERENCES

RIGHT

SELECT

SET

SHORT

SINGLE

SMALLINT — See SHORT

SOME

StDev

StDevP

STRING — See TEXT

Sum


(Untitled)

T-Z

TABLE

TableID*

TEXT

TIME — See DATETIME

TIMESTAMP — See DATETIME

TOP

TRANSFORM

UNION

UNIQUE

UPDATE

 VALUE

VALUES

Var

VARBINARY — See BINARY

VARCHAR — See TEXT

VarP

WHERE

WITH

Xor

YESNO — See BIT


ALTER TABLE Statement (Microsoft Jet SQL)

ALTER TABLE Statement

Modifies the design of a table after it has been created with the CREATE TABLE statement.

Note The Microsoft Jet database engine doesn't support the use of ALTER TABLE, or any of the data definition language (DDL) statements, with non-Microsoft Jet databases. Use the DAO Create methods instead.

Syntax

ALTER TABLE table {ADD {COLUMN field type[(size)] [NOT NULL] [CONSTRAINT index] |
CONSTRAINT multifieldindex} |
DROP {COLUMN field I CONSTRAINT indexname} }

The ALTER TABLE statement has these parts:

Part | Description
table | The name of the table to be altered.
field | The name of the field to be added to or deleted from table.
type | The data type of field.
size | The field size in characters (Text and Binary fields only).
index | The index for field. See the CONSTRAINT clause topic for more information on how to construct this index.
multifieldindex | The definition of a multiple-field index to be added to table. See the CONSTRAINT clause topic for more information on how to construct this clause.
indexname | The name of the multiple-field index to be removed.

Remarks

Using the ALTER TABLE statement, you can alter an existing table in several ways. You can:

  • Use ADD COLUMN to add a new field to the table. You specify the field name, data type, and (for Text and Binary fields) an optional size. For example, the following statement adds a 25-character Text field called Notes to the Employees table:
    ALTER TABLE Employees ADD COLUMN Notes TEXT(25)

    You can also define an index on that field. For more information on single-field indexes, see the CONSTRAINT clause topic.

    If you specify NOT NULL for a field, then new records are required to have valid data in that field.

  • Use ADD CONSTRAINT to add a multiple-field index. For more information on multiple-field indexes, see the CONSTRAINT clause topic.

  • Use DROP COLUMN to delete a field. You specify only the name of the field.

  • Use DROP CONSTRAINT to delete a multiple-field index. You specify only the index name following the CONSTRAINT reserved word.

Notes

  • You can't add or delete more than one field or index at a time.

  • You can use the CREATE INDEX statement to add a single- or multiple-field index to a table, and you can use ALTER TABLE or the DROP statement to delete an index created with ALTER TABLE or CREATE INDEX.

  • You can use NOT NULL on a single field, or within a named CONSTRAINT clause that applies to either a single field or to a multiple-field named CONSTRAINT. However, you can apply the NOT NULL restriction only once to a field, or a run-time error occurs.


CREATE INDEX Statement (Microsoft Jet SQL)

CREATE INDEX Statement

Creates a new index on an existing table.

Note For non-Microsoft Jet databases, the Microsoft Jet database engine doesn't support the use of CREATE INDEX (except to create a pseudo index on an ODBC linked table) or any of the data definition language (DDL) statements. Use the DAO Create methods instead. For more information, see the Remarks section.

Syntax

CREATE [ UNIQUE ] INDEX index
ON table (field [ASC|DESC][, field [ASC|DESC], ...])
[WITH { PRIMARY | DISALLOW NULL | IGNORE NULL }]

The CREATE INDEX statement has these parts:

Part | Description
index | The name of the index to be created.
table | The name of the existing table that will contain the index.
field | The name of the field or fields to be indexed. To create a single-field index, list the field name in parentheses following the table name. To create a multiple-field index, list the name of each field to be included in the index. To create descending indexes, use the DESC reserved word; otherwise, indexes are assumed to be ascending.

Remarks

To prohibit duplicate values in the indexed field or fields of different records, use the UNIQUE reserved word.

In the optional WITH clause, you can enforce data validation rules. You can:

  • Prohibit Null entries in the indexed field or fields of new records by using the DISALLOW NULL option.

  • Prevent records with Null values in the indexed field or fields from being included in the index by using the IGNORE NULL option.

  • Designate the indexed field or fields as the primary key by using the PRIMARY reserved word. This implies that the key is unique, so you can omit the UNIQUE reserved word.

You can use CREATE INDEX to create a pseudo index on a linked table in an ODBC data source, such as SQL Server, that does not already have an index. You don't need permission or access to the remote server to create a pseudo index, and the remote database is unaware of and unaffected by the pseudo index. You use the same syntax for both linked and native tables. This can be especially useful to create an index on a table that would ordinarily be read-only due to lack of an index.

You can also use the ALTER TABLE statement to add a single- or multiple-field index to a table, and you can use the ALTER TABLE statement or the DROP statement to remove an index created with ALTER TABLE or CREATE INDEX.

Note Don't use the PRIMARY reserved word when you create a new index on a table that already has a primary key; if you do, an error occurs.


CREATE TABLE Statement (Microsoft Jet SQL)

CREATE TABLE Statement

Creates a new table.

Note The Microsoft Jet database engine doesn't support the use of CREATE TABLE, or any of the DDL statements, with non-Microsoft Jet database engine databases. Use the DAO Create methods instead.

Syntax

CREATE TABLE table (field1 type [(size)] [NOT NULL] [index1] [, field2 type [(size)] [NOT NULL] [index2] [, ...]] [, CONSTRAINT multifieldindex [, ...]])

The CREATE TABLE statement has these parts:

Part | Description
table | The name of the table to be created.
field1, field2 | The name of field or fields to be created in the new table. You must create at least one field.
type | The data type of field in the new table.
size | The field size in characters (Text and Binary fields only).
index1, index2 | A CONSTRAINT clause defining a single-field index. See the CONSTRAINT clause topic for more information on how to create this index.
multifieldindex | A CONSTRAINT clause defining a multiple-field index. See the CONSTRAINT clause topic for more information on how to create this index.

Remarks

Use the CREATE TABLE statement to define a new table and its fields and field constraints. If NOT NULL is specified for a field, then new records are required to have valid data in that field.

A CONSTRAINT clause establishes various restrictions on a field, and can be used to establish the primary key. You can also use the CREATE INDEX statement to create a primary key or additional indexes on existing tables.

You can use NOT NULL on a single field, or within a named CONSTRAINT clause that applies to either a single field or to a multiple-field named CONSTRAINT. However, you can apply the NOT NULL restriction only once to a field, or a run-time error occurs.


DELETE Statement (Microsoft Jet SQL)

DELETE Statement

Creates a delete query that removes records from one or more of the tables listed in the FROM clause that satisfy the WHERE clause.

Syntax

DELETE [table.*]
FROM table
WHERE criteria

The DELETE statement has these parts:

Part | Description
table | The optional name of the table from which records are deleted.
table | The name of the table from which records are deleted.
criteria | An expression that determines which records to delete.

Remarks

DELETE is especially useful when you want to delete many records.

To drop an entire table from the database, you can use the Execute method with a DROP statement. If you delete the table, however, the structure is lost. In contrast, when you use DELETE, only the data is deleted; the table structure and all of the table properties, such as field attributes and indexes, remain intact.

You can use DELETE to remove records from tables that are in a one-to-many relationship with other tables. Cascade delete operations cause the records in tables that are on the many side of the relationship to be deleted when the corresponding record in the one side of the relationship is deleted in the query. For example, in the relationship between the Customers and Orders tables, the Customers table is on the one side and the Orders table is on the many side of the relationship. Deleting a record from Customers results in the corresponding Orders records being deleted if the cascade delete option is specified.

A delete query deletes entire records, not just data in specific fields. If you want to delete values in a specific field, create an update query that changes the values to Null.

Important

  • After you remove records using a delete query, you can't undo the operation. If you want to know which records were deleted, first examine the results of a select query that uses the same criteria, and then run the delete query.

  • Maintain backup copies of your data at all times. If you delete the wrong records, you can retrieve them from your backup copies.


DROP Statement (Microsoft Jet SQL)

DROP Statement

Deletes an existing table from a database or deletes an existing index from a table.

Note The Microsoft Jet database engine doesn't support the use of DROP, or any of the DDL statements, with non-Microsoft Jet databases. Use the DAO Delete method instead.

Syntax

DROP {TABLE table | INDEX index ON table}

The DROP statement has these parts:

Part | Description
table | The name of the table to be deleted or the table from which an index is to be deleted.
index | The name of the index to be deleted from table.

Remarks

You must close the table before you can delete it or remove an index from it.

You can also use ALTER TABLE to delete an index from a table.

You can use CREATE TABLE to create a table and CREATE INDEX or ALTER TABLE to create an index. To modify a table, use ALTER TABLE.


INSERT INTO Statement (Microsoft Jet SQL)

INSERT INTO Statement

Adds a record or multiple records to a table. This is referred to as an append query.

Syntax

Multiple-record append query:

INSERT INTO target [(field1[, field2[, ...]])] [IN externaldatabase]
SELECT [source.]field1[, field2[, ...]
FROM tableexpression

Single-record append query:

INSERT INTO target [(field1[, field2[, ...]])]
VALUES (value1[, value2[, ...])

The INSERT INTO statement has these parts:

Part | Description
target | The name of the table or query to append records to.
field1, field2 | Names of the fields to append data to, if following a target argument, or the names of fields to obtain data from, if following a source argument.
externaldatabase | The path to an external database. For a description of the path, see the IN clause.
source | The name of the table or query to copy records from.
tableexpression | The name of the table or tables from which records are inserted. This argument can be a single table name or a compound resulting from an INNER JOIN, LEFT JOIN, or RIGHT JOIN operation or a saved query.
value1, value2 | The values to insert into the specific fields of the new record. Each value is inserted into the field that corresponds to the value's position in the list: value1 is inserted into field1 of the new record, value2 into field2, and so on. You must separate values with a comma, and enclose text fields in quotation marks (' ').

Remarks

You can use the INSERT INTO statement to add a single record to a table using the single-record append query syntax as shown above. In this case, your code specifies the name and value for each field of the record. You must specify each of the fields of the record that a value is to be assigned to and a value for that field. When you don't specify each field, the default value or Null is inserted for missing columns. Records are added to the end of the table.

You can also use INSERT INTO to append a set of records from another table or query by using the SELECT ... FROM clause as shown above in the multiple-record append query syntax. In this case, the SELECT clause specifies the fields to append to the specified target table.

The source or target table may specify a table or a query. If a query is specified, the Microsoft Jet database engine appends records to any and all tables specified by the query.

INSERT INTO is optional but when included, precedes the SELECT statement.

If your destination table contains a primary key, make sure you append unique, non-Null values to the primary key field or fields; if you don't, the Microsoft Jet database engine won't append the records.

If you append records to a table with an AutoNumber field and you want to renumber the appended records, don't include the AutoNumber field in your query. Do include the AutoNumber field in the query if you want to retain the original values from the field.

Use the IN clause to append records to a table in another database.

To create a new table, use the SELECT... INTO statement instead to create a make-table query.

To find out which records will be appended before you run the append query, first execute and view the results of a select query that uses the same selection criteria.

An append query copies records from one or more tables to another. The tables that contain the records you append aren't affected by the append query.

Instead of appending existing records from another table, you can specify the value for each field in a single new record using the VALUES clause. If you omit the field list, the VALUES clause must include a value for every field in the table; otherwise, the INSERT operation will fail. Use an additional INSERT INTO statement with a VALUES clause for each additional record you want to create.


PARAMETERS Declaration (Microsoft Jet SQL)

PARAMETERS Declaration

Declares the name and data type of each parameter in a parameter query.

Syntax

PARAMETERS name datatype [, name datatype [, ...]]

The PARAMETERS declaration has these parts:

Part | Description
name | The name of the parameter. Assigned to the Name property of the Parameter object and used to identify this parameter in the Parameters collection. You can use name as a string that is displayed in a dialog box while your application runs the query. Use brackets ([ ]) to enclose text that contains spaces or punctuation. For example, [Low price] and [Begin report with which month?] are valid name arguments.
datatype | One of the primary Microsoft Jet SQL data types or their synonyms.

Remarks

For queries that you run regularly, you can use a PARAMETERS declaration to create a parameter query. A parameter query can help automate the process of changing query criteria. With a parameter query, your code will need to provide the parameters each time the query is run.

The PARAMETERS declaration is optional but when included precedes any other statement, including SELECT.

If the declaration includes more than one parameter, separate them with commas. The following example includes two parameters:

PARAMETERS [Low price] Currency, [Beginning date] DateTime;

You can use name but not datatype in a WHERE or HAVING clause. The following example expects two parameters to be provided and then applies the criteria to records in the Orders table:

PARAMETERS [Low price] Currency,
[Beginning date] DateTime;
SELECT OrderID, OrderAmount
FROM Orders
WHERE OrderAmount > [Low price]
AND OrderDate >= [Beginning date];


PROCEDURE Clause (Microsoft Jet SQL)

PROCEDURE Clause

Defines a name and optional parameters for a query.

Syntax

PROCEDURE name [param1 datatype[, param2 datatype[, ...]]

The PROCEDURE clause has these parts:

Part | Description
name | A name for the procedure. It must follow standard naming conventions.
param1, param2 | One or more field names or parameters. For example: PROCEDURE Sales_By_Country [Beginning Date] DateTime, [Ending Date] DateTime; For more information on parameters, see PARAMETERS.
datatype | One of the primary Microsoft Jet SQL data types or their synonyms.

Remarks

An SQL procedure consists of a PROCEDURE clause (which specifies the name of the procedure), an optional list of parameter definitions, and a single SQL statement. For example, the procedure Get_Part_Number might run a query that retrieves a specified part number.

Notes

  • If the clause includes more than one field definition (that is, param-datatype pairs), separate them with commas.

  • The PROCEDURE clause must be followed by an SQL statement (for example, a SELECT or UPDATE statement).


SELECT Statement (Microsoft Jet SQL)

SELECT Statement

Instructs the Microsoft Jet database engine to return information from the database as a set of records.

Syntax

SELECT [predicate] { * | table.* | [table.]field1 [AS alias1] [, [table.]field2 [AS alias2] [, ...]]}
FROM tableexpression [, ...] [IN externaldatabase]
[WHERE... ]
[GROUP BY... ]
[HAVING... ]
[ORDER BY... ]
[WITH OWNERACCESS OPTION]

The SELECT statement has these parts:

Part | Description
predicate | One of the following predicates: ALL, DISTINCT, DISTINCTROW, or TOP. You use the predicate to restrict the number of records returned. If none is specified, the default is ALL.
* | Specifies that all fields from the specified table or tables are selected.
table | The name of the table containing the fields from which records are selected.
field1, field2 | The names of the fields containing the data you want to retrieve. If you include more than one field, they are retrieved in the order listed.
alias1, alias2 | The names to use as column headers instead of the original column names in table.
tableexpression | The name of the table or tables containing the data you want to retrieve.
externaldatabase | The name of the database containing the tables in tableexpression if they are not in the current database.

Remarks

To perform this operation, the Microsoft Jet database engine searches the specified table or tables, extracts the chosen columns, selects rows that meet the criterion, and sorts or groups the resulting rows into the order specified.

SELECT statements don't change data in the database.

SELECT is usually the first word in an SQL statement. Most SQL statements are either SELECT or SELECT...INTO statements.

The minimum syntax for a SELECT statement is:

SELECT fields FROM table

You can use an asterisk (*) to select all fields in a table. The following example selects all of the fields in the Employees table:

SELECT * FROM Employees;

If a field name is included in more than one table in the FROM clause, precede it with the table name and the . (dot) operator. In the following example, the Department field is in both the Employees table and the Supervisors table. The SQL statement selects departments from the Employees table and supervisor names from the Supervisors table:

SELECT Employees.Department, Supervisors.SupvName
FROM Employees INNER JOIN Supervisors
WHERE Employees.Department = Supervisors.Department;

When a Recordset object is created, the Microsoft Jet database engine uses the table's field name as the Field object name in the Recordset object. If you want a different field name or a name isn't implied by the expression used to generate the field, use the AS reserved word. The following example uses the title Birth to name the returned Field object in the resulting Recordset object:

SELECT BirthDate
AS Birth FROM Employees;

Whenever you use aggregate functions or queries that return ambiguous or duplicate Field object names, you must use the AS clause to provide an alternate name for the Field object. The following example uses the title HeadCount to name the returned Field object in the resulting Recordset object:

SELECT COUNT(EmployeeID)
AS HeadCount FROM Employees;

You can use the other clauses in a SELECT statement to further restrict and organize your returned data. For more information, see the Help topic for the clause you're using.


SELECT...INTO Statement (Microsoft Jet SQL)

SELECT...INTO Statement

Creates a make-table query.

Syntax

SELECT field1[, field2[, ...]] INTO newtable [IN externaldatabase]
FROM source

The SELECT...INTO statement has these parts:

Part | Description
field1, field2 | The name of the fields to be copied into the new table.
newtable | The name of the table to be created. It must conform to standard naming conventions. If newtable is the same as the name of an existing table, a trappable error occurs.
externaldatabase | The path to an external database. For a description of the path, see the IN clause.
source | The name of the existing table from which records are selected. This can be single or multiple tables or a query.

Remarks

You can use make-table queries to archive records, make backup copies of your tables, or make copies to export to another database or to use as a basis for reports that display data for a particular time period. For example, you could produce a Monthly Sales by Region report by running the same make-table query each month.

Notes

  • You may want to define a primary key for the new table. When you create the table, the fields in the new table inherit the data type and field size of each field in the query's underlying tables, but no other field or table properties are transferred.

  • To add data to an existing table, use the INSERT INTO statement instead to create an append query.

  • To find out which records will be selected before you run the make-table query, first examine the results of a SELECT statement that uses the same selection criteria.


TRANSFORM Statement (Microsoft Jet SQL)

TRANSFORM Statement

Creates a crosstab query.

Syntax

TRANSFORM aggfunction
selectstatement
PIVOT pivotfield [IN (value1[, value2[, ...]])]

The TRANSFORM statement has these parts:

Part | Description
aggfunction | An SQL aggregate function that operates on the selected data.
selectstatement | A SELECT statement.
pivotfield | The field or expression you want to use to create column headings in the query's result set.
value1, value2 | Fixed values used to create column headings.

Remarks

When you summarize data using a crosstab query, you select values from specified fields or expressions as column headings so you can view data in a more compact format than with a select query.

TRANSFORM is optional but when included is the first statement in an SQL string. It precedes a SELECT statement that specifies the fields used as row headings and a GROUP BY clause that specifies row grouping. Optionally, you can include other clauses, such as WHERE, that specify additional selection or sorting criteria. You can also use subqueries as predicates — specifically, those in the WHERE clause — in a crosstab query.

The values returned in pivotfield are used as column headings in the query's result set. For example, pivoting the sales figures on the month of the sale in a crosstab query would create 12 columns. You can restrict pivotfield to create headings from fixed values (value1, value2 ) listed in the optional IN clause. You can also include fixed values for which no data exists to create additional columns.


UNION Operation (Microsoft Jet SQL)

UNION Operation

Creates a union query, which combines the results of two or more independent queries or tables.

Syntax

[TABLE] query1 UNION [ALL] [TABLE] query2 [UNION [ALL] [TABLE] queryn [ ... ]]

The UNION operation has these parts:

Part | Description
query1-n | A SELECT statement, the name of a stored query, or the name of a stored table preceded by the TABLE keyword.

Remarks

You can merge the results of two or more queries, tables, and SELECT statements, in any combination, in a single UNION operation. The following example merges an existing table named New Accounts and a SELECT statement:

TABLE [New Accounts] UNION ALL
SELECT *
FROM Customers
WHERE OrderAmount > 1000;

By default, no duplicate records are returned when you use a UNION operation; however, you can include the ALL predicate to ensure that all records are returned. This also makes the query run faster.

All queries in a UNION operation must request the same number of fields; however, the fields don't have to be of the same size or data type.

Use aliases only in the first SELECT statement because they are ignored in any others. In the ORDER BY clause, refer to fields by what they are called in the first SELECT statement.

Notes

  • You can use a GROUP BY or HAVING clause in each query argument to group the returned data.

  • You can use an ORDER BY clause at the end of the last query argument to display the returned data in a specified order.


UPDATE Statement (Microsoft Jet SQL)

UPDATE Statement

Creates an update query that changes values in fields in a specified table based on specified criteria.

Syntax

UPDATE table
SET newvalue
WHERE criteria;

The UPDATE statement has these parts:

Part | Description
table | The name of the table containing the data you want to modify.
newvalue | An expression that determines the value to be inserted into a particular field in the updated records.
criteria | An expression that determines which records will be updated. Only records that satisfy the expression are updated.

Remarks

UPDATE is especially useful when you want to change many records or when the records that you want to change are in multiple tables.

You can change several fields at the same time. The following example increases the Order Amount values by 10 percent and the Freight values by 3 percent for shippers in the United Kingdom:

UPDATE Orders
SET OrderAmount = OrderAmount * 1.1,
Freight = Freight * 1.03
WHERE ShipCountry = 'UK';

Important

  • UPDATE doesn't generate a result set. Also, after you update records using an update query, you can't undo the operation. If you want to know which records were updated, first examine the results of a select query that uses the same criteria, and then run the update query.

  • Maintain backup copies of your data at all times. If you update the wrong records, you can retrieve them from your backup copies.


WITH OWNERACCESS OPTION Declaration (Microsoft Jet SQL)

WITH OWNERACCESS OPTION Declaration

In a multiuser environment with a secure workgroup, use this declaration with a query to give the user who runs the query the same permissions as the query's owner.

Syntax

sqlstatement
WITH OWNERACCESS OPTION

Remarks

The WITH OWNERACCESS OPTION declaration is optional.

The following example enables the user to view salary information (even if the user doesn't otherwise have permission to view the Payroll table), provided that the query's owner does have that permission:

SELECT LastName,
FirstName, Salary
FROM Employees
ORDER BY LastName
WITH OWNERACCESS OPTION;

If a user is otherwise prevented from creating or adding to a table, you can use WITH OWNERACCESS OPTION to enable the user to run a make-table or append query.

If you want to enforce workgroup security settings and users' permissions, don't include the WITH OWNERACCESS OPTION declaration.

This option requires you to have access to the System.mdw file associated with the database. It's really useful only in secured multiuser implementations.


ALL, DISTINCT, DISTINCTROW, TOP Predicates (Microsoft Jet SQL)

ALL, DISTINCT, DISTINCTROW, TOP Predicates

Specifies records selected with SQL queries.

Syntax

SELECT [ALL | DISTINCT | DISTINCTROW | [TOP n [PERCENT]]]
FROM table

A SELECT statement containing these predicates has the following parts:

Part | Description
ALL Assumed if you don't include one of the predicates. The Microsoft Jet database engine selects all of the records that meet the conditions in the SQL statement. The following two examples are equivalent and return all records from the Employees table:

SELECT ALL *
FROM Employees
ORDER BY EmployeeID;

SELECT *
FROM Employees
ORDER BY EmployeeID;
DISTINCT Omits records that contain duplicate data in the selected fields. To be included in the results of the query, the values for each field listed in the SELECT statement must be unique. For example, several employees listed in an Employees table may have the same last name. If two records contain Smith in the LastName field, the following SQL statement returns only one record that contains Smith:

SELECT DISTINCT
LastName
FROM Employees;

If you omit DISTINCT, this query returns both Smith records.

If the SELECT clause contains more than one field, the combination of values from all fields must be unique for a given record to be included in the results.

The output of a query that uses DISTINCT isn't updatable and doesn't reflect subsequent changes made by other users.
DISTINCTROW Omits data based on entire duplicate records, not just duplicate fields. For example, you could create a query that joins the Customers and Orders tables on the CustomerID field. The Customers table contains no duplicate CustomerID fields, but the Orders table does because each customer can have many orders. The following SQL statement shows how you can use DISTINCTROW to produce a list of companies that have at least one order but without any details about those orders:

SELECT DISTINCTROW CompanyName
FROM Customers INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
ORDER BY CompanyName;

If you omit DISTINCTROW, this query produces multiple rows for each company that has more than one order.

DISTINCTROW has an effect only when you select fields from some, but not all, of the tables used in the query. DISTINCTROW is ignored if your query includes only one table, or if you output fields from all tables.
TOP n [PERCENT] Returns a certain number of records that fall at the top or the bottom of a range specified by an ORDER BY clause. Suppose you want the names of the top 25 students from the class of 1994:

SELECT TOP 25
FirstName, LastName
FROM Students
WHERE GraduationYear = 1994
ORDER BY GradePointAverage DESC;

If you don't include the ORDER BY clause, the query will return an arbitrary set of 25 records from the Students table that satisfy the WHERE clause.

The TOP predicate doesn't choose between equal values. In the preceding example, if the twenty-fifth and twenty-sixth highest grade point averages are the same, the query will return 26 records.

You can also use the PERCENT reserved word to return a certain percentage of records that fall at the top or the bottom of a range specified by an ORDER BY clause. Suppose that, instead of the top 25 students, you want the bottom 10 percent of the class:

SELECT TOP 10 PERCENT
FirstName, LastName
FROM Students
WHERE GraduationYear = 1994
ORDER BY GradePointAverage ASC;

The ASC predicate specifies a return of bottom values. The value that follows TOP must be an unsigned Integer.

TOP doesn't affect whether or not the query is updatable.
table | The name of the table from which records are retrieved.


CONSTRAINT Clause (Microsoft Jet SQL)

CONSTRAINT Clause

A constraint is similar to an index, although it can also be used to establish a relationship with another table.

You use the CONSTRAINT clause in ALTER TABLE and CREATE TABLE statements to create or delete constraints. There are two types of CONSTRAINT clauses: one for creating a constraint on a single field and one for creating a constraint on more than one field.

Note The Microsoft Jet database engine doesn't support the use of CONSTRAINT, or any of the data definition language (DDL) statements, with non-Microsoft Jet databases. Use the DAO Create methods instead.

Syntax

Single-field constraint:

CONSTRAINT name {PRIMARY KEY | UNIQUE | NOT NULL |
REFERENCES foreigntable [(foreignfield1, foreignfield2)]}

Multiple-field constraint:

CONSTRAINT name
{PRIMARY KEY (primary1[, primary2 [, ...]]) |
UNIQUE (unique1[, unique2 [, ...]]) |
NOT NULL (notnull1[, notnull2 [, ...]]) |
FOREIGN KEY (ref1[, ref2 [, ...]]) REFERENCES foreigntable [(foreignfield1 [, foreignfield2 [, ...]])]}

The CONSTRAINT clause has these parts:

Part | Description
name | The name of the constraint to be created.
primary1, primary2 | The name of the field or fields to be designated the primary key.
unique1, unique2 | The name of the field or fields to be designated as a unique key.
notnull1, notnull2 | The name of the field or fields that are restricted to non-Null values.
ref1, ref2 | The name of a foreign key field or fields that refer to fields in another table.
foreigntable | The name of the foreign table containing the field or fields specified by foreignfield.
foreignfield1, foreignfield2 | The name of the field or fields in foreigntable specified by ref1, ref2. You can omit this clause if the referenced field is the primary key of foreigntable.

Remarks

You use the syntax for a single-field constraint in the field-definition clause of an ALTER TABLE or CREATE TABLE statement immediately following the specification of the field's data type.

You use the syntax for a multiple-field constraint whenever you use the reserved word CONSTRAINT outside a field-definition clause in an ALTER TABLE or CREATE TABLE statement.

Using CONSTRAINT, you can designate a field as one of the following types of constraints:

  • You can use the UNIQUE reserved word to designate a field as a unique key. This means that no two records in the table can have the same value in this field. You can constrain any field or list of fields as unique. If a multiple-field constraint is designated as a unique key, the combined values of all fields in the index must be unique, even if two or more records have the same value in just one of the fields.

  • You can use the PRIMARY KEY reserved words to designate one field or set of fields in a table as a primary key. All values in the primary key must be unique and not Null, and there can be only one primary key for a table.

    Note Don't set a PRIMARY KEY constraint on a table that already has a primary key; if you do, an error occurs.

  • You can use the FOREIGN KEY reserved words to designate a field as a foreign key. If the foreign table's primary key consists of more than one field, you must use a multiple-field constraint definition, listing all of the referencing fields, the name of the foreign table, and the names of the referenced fields in the foreign table in the same order that the referencing fields are listed. If the referenced field or fields are the foreign table's primary key, you don't have to specify the referenced fields — by default, the database engine behaves as if the foreign table's primary key is the referenced fields.


FROM Clause (Microsoft Jet SQL)

FROM Clause

Specifies the tables or queries that contain the fields listed in the SELECT statement.

Syntax

SELECT fieldlist
FROM tableexpression [IN externaldatabase]

A SELECT statement containing a FROM clause has these parts:

Part | Description
fieldlist | The name of the field or fields to be retrieved along with any field-name aliases, SQL aggregate functions, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.
tableexpression | An expression that identifies one or more tables from which data is retrieved. The expression can be a single table name, a saved query name, or a compound resulting from an INNER JOIN, LEFT JOIN, or RIGHT JOIN.
externaldatabase | The full path of an external database containing all the tables in tableexpression.

Remarks

FROM is required and follows any SELECT statement.

The order of the table names in tableexpression isn't important.

For improved performance and ease of use, it's recommended that you use a linked table instead of an IN clause to retrieve data from an external database.

The following example shows how you can retrieve data from the Employees table:

SELECT LastName, FirstName
FROM Employees;


GROUP BY Clause (Microsoft Jet SQL)

GROUP BY Clause

Combines records with identical values in the specified field list into a single record. A summary value is created for each record if you include an SQL aggregate function, such as Sum or Count, in the SELECT statement.

Syntax

SELECT fieldlist
FROM table
WHERE criteria
[GROUP BY groupfieldlist]

A SELECT statement containing a GROUP BY clause has these parts:

Part | Description
fieldlist | The name of the field or fields to be retrieved along with any field-name aliases, SQL aggregate functions, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.
table | The name of the table from which records are retrieved. For more information, see the FROM clause.
criteria | Selection criteria. If the statement includes a WHERE clause, the Microsoft Jet database engine groups values after applying the WHERE conditions to the records.
groupfieldlist | The names of up to 10 fields used to group records. The order of the field names in groupfieldlist determines the grouping levels from the highest to the lowest level of grouping.

Remarks

GROUP BY is optional.

Summary values are omitted if there is no SQL aggregate function in the SELECT statement.

Null values in GROUP BY fields are grouped and aren't omitted. However, Null values aren't evaluated in any SQL aggregate function.

Use the WHERE clause to exclude rows you don't want grouped, and use the HAVING clause to filter records after they've been grouped.

Unless it contains Memo or OLE Object data, a field in the GROUP BY field list can refer to any field in any table listed in the FROM clause, even if the field isn't included in the SELECT statement, provided the SELECT statement includes at least one SQL aggregate function. The Microsoft Jet database engine can't group on Memo or OLE Object fields.

All fields in the SELECT field list must either be included in the GROUP BY clause or be included as arguments to an SQL aggregate function.


HAVING Clause (Microsoft Jet SQL)

HAVING Clause

Specifies which grouped records are displayed in a SELECT statement with a GROUP BY clause. After GROUP BY combines records, HAVING displays any records grouped by the GROUP BY clause that satisfy the conditions of the HAVING clause.

Syntax

SELECT fieldlist
FROM table
WHERE selectcriteria
GROUP BY groupfieldlist
[HAVING groupcriteria]

A SELECT statement containing a HAVING clause has these parts:

Part | Description
fieldlist | The name of the field or fields to be retrieved along with any field-name aliases, SQL aggregate functions, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.
table | The name of the table from which records are retrieved. For more information, see the FROM clause.
selectcriteria | Selection criteria. If the statement includes a WHERE clause, the Microsoft Jet database engine groups values after applying the WHERE conditions to the records.
groupfieldlist | The names of up to 10 fields used to group records. The order of the field names in groupfieldlist determines the grouping levels from the highest to the lowest level of grouping.
groupcriteria | An expression that determines which grouped records to display.

Remarks

HAVING is optional.

HAVING is similar to WHERE, which determines which records are selected. After records are grouped with GROUP BY, HAVING determines which records are displayed:

SELECT CategoryID,
Sum(UnitsInStock)
FROM Products
GROUP BY CategoryID
HAVING Sum(UnitsInStock) > 100 And Like "BOS*";

A HAVING clause can contain up to 40 expressions linked by logical operators, such as And and Or.


IN Clause (Microsoft Jet SQL)

IN Clause

Identifies tables in any external database to which the Microsoft Jet database engine can connect, such as a dBASE or Paradox database or an external Microsoft Jet database.

Syntax

To identify a destination table:

[SELECT | INSERT] INTO destination IN
{path | ["path" "type"] | ["" [type; DATABASE = path]]}

To identify a source table:

FROM tableexpression IN
{path | ["path" "type"] | ["" [type; DATABASE = path]]}

A SELECT statement containing an IN clause has these parts:

Part | Description
destination | The name of the external table into which data is inserted.
tableexpression | The name of the table or tables from which data is retrieved. This argument can be a single table name, a saved query, or a compound resulting from an INNER JOIN, LEFT JOIN, or RIGHT JOIN.
path | The full path for the directory or file containing table.
type | The name of the database type used to create table if a database isn't a Microsoft Jet database (for example, dBASE III, dBASE IV, Paradox 3.x, or Paradox 4.x).

Remarks

You can use IN to connect to only one external database at a time.

In some cases, the path argument refers to the directory containing the database files. For example, when working with dBASE, FoxPro, or Paradox database tables, the path argument specifies the directory containing .dbf or .db files. The table file name is derived from the destination or tableexpression argument.

To specify a non-Microsoft Jet database, append a semicolon (;) to the name, and enclose it in single (' ') or double (" ") quotation marks. For example, either 'dBASE IV;' or "dBASE IV;" is acceptable.

You can also use the DATABASE reserved word to specify the external database. For example, the following lines specify the same table:

... FROM Table IN "" [dBASE IV; DATABASE=C:\DBASE\DATA\SALES;];
... FROM Table IN "C:\DBASE\DATA\SALES" "dBASE IV;"

Notes

  • For improved performance and ease of use, use a linked table instead of IN.

  • You can also use the IN reserved word as a comparison operator in an expression. For more information, see the In operator.


INNER JOIN Operation (Microsoft Jet SQL)

INNER JOIN Operation

Combines records from two tables whenever there are matching values in a common field.

Syntax

FROM table1 INNER JOIN table2 ON table1.field1 compopr table2.field2

The INNER JOIN operation has these parts:

Part | Description
table1, table2 | The names of the tables from which records are combined.
field1, field2 | The names of the fields that are joined. If they aren't numeric, the fields must be of the same data type and contain the same kind of data, but they don't have to have the same name.
compopr | Any relational comparison operator: "=," "<," ">," "<=," ">=," or "<>."

Remarks

You can use an INNER JOIN operation in any FROM clause. This is the most common type of join. Inner joins combine records from two tables whenever there are matching values in a field common to both tables.

You can use INNER JOIN with the Departments and Employees tables to select all the employees in each department. In contrast, to select all departments (even if some have no employees assigned to them) or all employees (even if some aren't assigned to a department), you can use a LEFT JOIN or RIGHT JOIN operation to create an outer join.

If you try to join fields containing Memo or OLE Object data, an error occurs.

You can join any two numeric fields of like types. For example, you can join on AutoNumber and Long fields because they are like types. However, you cannot join Single and Double types of fields.

The following example shows how you could join the Categories and Products tables on the CategoryID field:

SELECT CategoryName, ProductName
FROM Categories INNER JOIN Products
ON Categories.CategoryID = Products.CategoryID;

In the preceding example, CategoryID is the joined field, but it isn't included in the query output because it isn't included in the SELECT statement. To include the joined field, include the field name in the SELECT statement ? in this case, Categories.CategoryID.

You can also link several ON clauses in a JOIN statement, using the following syntax:

SELECT fields
FROM table1 INNER JOIN table2
ON table1.field1 compopr table2.field1 AND
ON table1.field2 compopr table2.field2) OR
ON table1.field3 compopr table2.field3)];

You can also nest JOIN statements using the following syntax:

SELECT fields
FROM table1 INNER JOIN
(table2 INNER JOIN [( ]table3
[INNER JOIN [( ]tablex [INNER JOIN ...)]
ON table3.field3 compopr tablex.fieldx)]
ON table2.field2 compopr table3.field3)
ON table1.field1 compopr table2.field2;

A LEFT JOIN or a RIGHT JOIN may be nested inside an INNER JOIN, but an INNER JOIN may not be nested inside a LEFT JOIN or a RIGHT JOIN.


LEFT JOIN, RIGHT JOIN Operations (Microsoft Jet SQL)

LEFT JOIN, RIGHT JOIN Operations

Combines source-table records when used in any FROM clause.

Syntax

FROM table1 [ LEFT | RIGHT ] JOIN table2
ON table1.field1 compopr table2.field2

The LEFT JOIN and RIGHT JOIN operations have these parts:

Part | Description
table1, table2 | The names of the tables from which records are combined.
field1, field2 | The names of the fields that are joined. The fields must be of the same data type and contain the same kind of data, but they don't need to have the same name.
compopr | Any relational comparison operator: "=," "<," ">," "<=," ">=," or "<>."

Remarks

Use a LEFT JOIN operation to create a left outer join. Left outer joins include all of the records from the first (left) of two tables, even if there are no matching values for records in the second (right) table.

Use a RIGHT JOIN operation to create a right outer join. Right outer joins include all of the records from the second (right) of two tables, even if there are no matching values for records in the first (left) table.

For example, you could use LEFT JOIN with the Departments (left) and Employees (right) tables to select all departments, including those that have no employees assigned to them. To select all employees, including those who aren't assigned to a department, you would use RIGHT JOIN.

The following example shows how you could join the Categories and Products tables on the CategoryID field. The query produces a list of all categories, including those that contain no products:

SELECT CategoryName,
ProductName
FROM Categories LEFT JOIN Products
ON Categories.CategoryID = Products.CategoryID;

In this example, CategoryID is the joined field, but it isn't included in the query results because it isn't included in the SELECT statement. To include the joined field, enter the field name in the SELECT statement — in this case, Categories.CategoryID.

Notes

  • To create a query that includes only records in which the data in the joined fields is the same, use an INNER JOIN operation.

  • A LEFT JOIN or a RIGHT JOIN can be nested inside an INNER JOIN, but an INNER JOIN cannot be nested inside a LEFT JOIN or a RIGHT JOIN. See the discussion of nesting in the INNER JOIN topic to see how to nest joins within other joins.

  • You can link multiple ON clauses. See the discussion of clause linking in the INNER JOIN topic to see how this is done.

  • If you try to join fields containing Memo or OLE Object data, an error occurs.


ORDER BY Clause (Microsoft Jet SQL)

ORDER BY Clause

Sorts a query's resulting records on a specified field or fields in ascending or descending order.

Syntax

SELECT fieldlist
FROM table
WHERE selectcriteria
[ORDER BY field1 [ASC | DESC ][, field2 [ASC | DESC ]][, ...]]]

A SELECT statement containing an ORDER BY clause has these parts:

Part | Description
fieldlist | The name of the field or fields to be retrieved along with any field-name aliases, SQL aggregate functions, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.
table | The name of the table from which records are retrieved. For more information, see the FROM clause.
selectcriteria | Selection criteria. If the statement includes a WHERE clause, the Microsoft Jet database engine orders values after applying the WHERE conditions to the records.
field1, field2 | The names of the fields on which to sort records.

Remarks

ORDER BY is optional. However, if you want your data displayed in sorted order, then you must use ORDER BY.

The default sort order is ascending (A to Z, 0 to 9). Both of the following examples sort employee names in last name order:

SELECT LastName, FirstName
FROM Employees
ORDER BY LastName;

SELECT LastName, FirstName
FROM Employees
ORDER BY LastName ASC;

To sort in descending order (Z to A, 9 to 0), add the DESC reserved word to the end of each field you want to sort in descending order. The following example selects salaries and sorts them in descending order:

SELECT LastName, Salary
FROM Employees
ORDER BY Salary DESC, LastName;

If you specify a field containing Memo or OLE Object data in the ORDER BY clause, an error occurs. The Microsoft Jet database engine doesn't sort on fields of these types.

ORDER BY is usually the last item in an SQL statement.

You can include additional fields in the ORDER BY clause. Records are sorted first by the first field listed after ORDER BY. Records that have equal values in that field are then sorted by the value in the second field listed, and so on.


SQL Subqueries

A subquery is a SELECT statement nested inside a SELECT, SELECT...INTO, INSERT...INTO, DELETE, or UPDATE statement or inside another subquery.

Syntax

You can use three forms of syntax to create a subquery:

comparison [ANY | ALL | SOME] (sqlstatement)

expression [NOT] IN (sqlstatement)

[NOT] EXISTS (sqlstatement)

A subquery has these parts:

Part | Description
comparison | An expression and a comparison operator that compares the expression with the results of the subquery.
expression | An expression for which the result set of the subquery is searched.
sqlstatement | A SELECT statement, following the same format and rules as any other SELECT statement. It must be enclosed in parentheses.

Remarks

You can use a subquery instead of an expression in the field list of a SELECT statement or in a WHERE or HAVING clause. In a subquery, you use a SELECT statement to provide a set of one or more specific values to evaluate in the WHERE or HAVING clause expression.

Use the ANY or SOME predicate, which are synonymous, to retrieve records in the main query that satisfy the comparison with any records retrieved in the subquery. The following example returns all products whose unit price is greater than that of any product sold at a discount of 25 percent or more:

SELECT * FROM Products
WHERE UnitPrice > ANY
(SELECT UnitPrice FROM OrderDetails
WHERE Discount >= .25);

Use the ALL predicate to retrieve only those records in the main query that satisfy the comparison with all records retrieved in the subquery. If you changed ANY to ALL in the previous example, the query would return only those products whose unit price is greater than that of all products sold at a discount of 25 percent or more. This is much more restrictive.

Use the IN predicate to retrieve only those records in the main query for which some record in the subquery contains an equal value. The following example returns all products with a discount of 25 percent or more:

SELECT * FROM Products
WHERE ProductID IN
(SELECT ProductID FROM OrderDetails
WHERE Discount >= .25);

Conversely, you can use NOT IN to retrieve only those records in the main query for which no record in the subquery contains an equal value.

Use the EXISTS predicate (with the optional NOT reserved word) in true/false comparisons to determine whether the subquery returns any records.

You can also use table name aliases in a subquery to refer to tables listed in a FROM clause outside the subquery. The following example returns the names of employees whose salaries are equal to or greater than the average salary of all employees having the same job title. The Employees table is given the alias "T1":

SELECT LastName,
FirstName, Title, Salary
FROM Employees AS T1
WHERE Salary >=
(SELECT Avg(Salary)
FROM Employees
WHERE T1.Title = Employees.Title) Order by Title;

In the preceding example, the AS reserved word is optional.

Some subqueries are allowed in crosstab queries — specifically, as predicates (those in the WHERE clause). Subqueries as output (those in the SELECT list) are not allowed in crosstab queries.


WHERE Clause (Microsoft Jet SQL)

WHERE Clause

Specifies which records from the tables listed in the FROM clause are affected by a SELECT, UPDATE, or DELETE statement.

Syntax

SELECT fieldlist
FROM tableexpression
WHERE criteria

A SELECT statement containing a WHERE clause has these parts:

Part | Description
fieldlist | The name of the field or fields to be retrieved along with any field-name aliases, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.
tableexpression | The name of the table or tables from which data is retrieved.
criteria | An expression that records must satisfy to be included in the query results.

Remarks

The Microsoft Jet database engine selects the records that meet the conditions listed in the WHERE clause. If you don't specify a WHERE clause, your query returns all rows from the table. If you specify more than one table in your query and you haven't included a WHERE clause or a JOIN clause, your query generates a Cartesian product of the tables.

WHERE is optional, but when included, follows FROM. For example, you can select all employees in the sales department (WHERE Dept = 'Sales') or all customers between the ages of 18 and 30 (WHERE Age Between 18 And 30).

If you don't use a JOIN clause to perform SQL join operations on multiple tables, the resulting Recordset object won't be updatable.

WHERE is similar to HAVING. WHERE determines which records are selected. Similarly, once records are grouped with GROUP BY, HAVING determines which records are displayed.

Use the WHERE clause to eliminate records you don't want grouped by a GROUP BY clause.

Use various expressions to determine which records the SQL statement returns. For example, the following SQL statement selects all employees whose salaries are more than $21,000:

SELECT LastName, Salary
FROM Employees
WHERE Salary > 21000;

A WHERE clause can contain up to 40 expressions linked by logical operators, such as And and Or.

When you enter a field name that contains a space or punctuation, surround the name with brackets ([ ]). For example, a customer information table might include information about specific customers :

SELECT [Customer’s Favorite Restarant]

When you specify the criteria argument, date literals must be in U.S. format, even if you're not using the U.S. version of the Microsoft Jet database engine. For example, May 10, 1996, is written 10/5/96 in the United Kingdom and 5/10/96 in the United States. Be sure to enclose your date literals with the number sign (#) as shown in the following examples.

To find records dated May 10, 1996 in a United Kingdom database, you must use the following SQL statement:

SELECT *
FROM Orders
WHERE ShippedDate = #5/10/96#;

You can also use the DateValue function which is aware of the international settings established by Microsoft Windows. For example, use this code for the United States:

SELECT *
FROM Orders
WHERE ShippedDate = DateValue('5/10/96');

And use this code for the United Kingdom:

SELECT *
FROM Orders
WHERE ShippedDate = DateValue('10/5/96');

Note If the column referenced in the criteria string is of type GUID, the criteria expression uses a slightly different syntax:

WHERE ReplicaID = {GUID {12345678-90AB-CDEF-1234-567890ABCDEF}}

Be sure to include the nested braces and hyphens as shown.


SQL Aggregate Functions (SQL)

SQL Aggregate Functions

Using the SQL aggregate functions, you can determine various statistics on sets of values. You can use these functions in a query and aggregate expressions in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.

Avg Function

Count Function

Min, Max Functions

StDev, StDevP Functions

Sum Function

Var, VarP Functions


Avg Function (Microsoft Jet SQL)

Avg Function

Calculates the arithmetic mean of a set of values contained in a specified field on a query.

Syntax

Avg(expr)

The expr placeholder represents a string expression identifying the field that contains the numeric data you want to average or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate functions).

Remarks

The average calculated by Avg is the arithmetic mean (the sum of the values divided by the number of values). You could use Avg, for example, to calculate average freight cost.

The Avg function doesn't include any Null fields in the calculation.

You can use Avg in a query expression and in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.


Count Function (Microsoft Jet SQL)

Count Function

Calculates the number of records returned by a query.

Syntax

Count(expr)

The expr placeholder represents a string expression identifying the field that contains the data you want to count or an expression that performs a calculation using the data in the field. Operands in expr can include the name of a table field or function (which can be either intrinsic or user-defined but not other SQL aggregate functions). You can count any kind of data, including text.

Remarks

You can use Count to count the number of records in an underlying query. For example, you could use Count to count the number of orders shipped to a particular country.

Although expr can perform a calculation on a field, Count simply tallies the number of records. It doesn't matter what values are stored in the records.

The Count function doesn't count records that have Null fields unless expr is the asterisk (*) wildcard character. If you use an asterisk, Count calculates the total number of records, including those that contain Null fields. Count(*) is considerably faster than Count([Column Name]). Don't enclose the asterisk in quotation marks (' '). The following example calculates the number of records in the Orders table:

SELECT Count(*)
AS TotalOrders FROM Orders;

If expr identifies multiple fields, the Count function counts a record only if at least one of the fields is not Null. If all of the specified fields are Null, the record isn't counted. Separate the field names with an ampersand (&). The following example shows how you can limit the count to records in which either ShippedDate or Freight isn't Null:

SELECT
Count('ShippedDate & Freight')
AS [Not Null] FROM Orders;

You can use Count in a query expression. You can also use this expression in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.


First, Last Functions (Microsoft Jet SQL)

First, Last Functions

Return a field value from the first or last record in the result set returned by a query.

Syntax

First(expr)

Last(expr)

The expr placeholder represents a string expression identifying the field that contains the data you want to use or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate functions).

Remarks

The First and Last functions are analogous to the MoveFirst and MoveLast methods of a DAO Recordset object. They simply return the value of a specified field in the first or last record, respectively, of the result set returned by a query. Because records are usually returned in no particular order (unless the query includes an ORDER BY clause), the records returned by these functions will be arbitrary.


Min, Max Functions (Microsoft Jet SQL)

Min, Max Functions

Return the minimum or maximum of a set of values contained in a specified field on a query.

Syntax

Min(expr)

Max(expr)

The expr placeholder represents a string expression identifying the field that contains the data you want to evaluate or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate functions).

Remarks

You can use Min and Max to determine the smallest and largest values in a field based on the specified aggregation, or grouping. For example, you could use these functions to return the lowest and highest freight cost. If there is no aggregation specified, then the entire table is used.

You can use Min and Max in a query expression and in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.


StDev, StDevP Functions (Microsoft Jet SQL)

StDev, StDevP Functions

Return estimates of the standard deviation for a population or a population sample represented as a set of values contained in a specified field on a query.

Syntax

StDev(expr)

StDevP(expr)

The expr placeholder represents a string expression identifying the field that contains the numeric data you want to evaluate or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate functions).

Remarks

The StDevP function evaluates a population, and the StDev function evaluates a population sample.

If the underlying query contains fewer than two records (or no records, for the StDevP function), these functions return a Null value (which indicates that a standard deviation can't be calculated).

You can use the StDev and StDevP functions in a query expression. You can also use this expression in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.


Sum Function (Microsoft Jet SQL)

Sum Function

Returns the sum of a set of values contained in a specified field on a query.

Syntax

Sum(expr)

The expr placeholder represents a string expression identifying the field that contains the numeric data you want to add or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate functions).

Remarks

The Sum function totals the values in a field. For example, you could use the Sum function to determine the total cost of freight charges.

The Sum function ignores records that contain Null fields. The following example shows how you can calculate the sum of the products of UnitPrice and Quantity fields:

SELECT
Sum(UnitPrice * Quantity)
AS [Total Revenue] FROM [Order Details];

You can use the Sum function in a query expression. You can also use this expression in the SQL property of a QueryDef object or when creating a Recordset based on an SQL query.


Var, VarP Functions (Microsoft Jet SQL)

Var, VarP Functions

Return estimates of the variance for a population or a population sample represented as a set of values contained in a specified field on a query.

Syntax

Var(expr)

VarP(expr)

The expr placeholder represents a string expression identifying the field that contains the numeric data you want to evaluate or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate functions).

Remarks

The VarP function evaluates a population, and the Var function evaluates a population sample.

If the underlying query contains fewer than two records, the Var and VarP functions return a Null value, which indicates that a variance can't be calculated.

You can use the Var and VarP functions in a query expression or in an SQL statement.


Calculating Fields in SQL Functions

You can use the string expression argument in an SQL aggregate function to perform a calculation on values in a field. For example, you could calculate a percentage (such as a surcharge or sales tax) by multiplying a field value by a fraction.

The following table provides examples of calculations on fields from the Orders and Order Details tables in the Northwind.mdb database.

Calculation | Example
Add a number to a field | Freight + 5
Subtract a number from a field | Freight - 5
Multiply a field by a number | UnitPrice * 2
Divide a field by a number | Freight / 2
Add one field to another | UnitsInStock + UnitsOnOrder
Subtract one field from another | ReorderLevel - UnitsInStock

The following example calculates the average discount amount of all orders in the Northwind.mdb database. It multiplies the values in the UnitPrice and Discount fields to determine the discount amount of each order and then calculates the average. You can use this expression in an SQL statement in Visual Basic code:

SELECT Avg(UnitPrice * Discount) AS [Average Discount] FROM [Order Details];


ALTER TABLE Statement Example (DAO)

ALTER TABLE Statement Example

This example adds a Salary field with a data type of Currency to the Employees table.

Sub AlterTableX1()

   Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Add the Salary field to the Employees table
   ' and make it a Currency data type.
   dbs.Execute "ALTER TABLE Employees " _
      & "ADD COLUMN Salary CURRENCY;"

   dbs.Close

End Sub

This example removes the Salary field from the Employees table.

Sub AlterTableX2()

   Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Delete the Salary field from the Employees table.
   dbs.Execute "ALTER TABLE Employees " _
      & "DROP COLUMN Salary;"

   dbs.Close

End Sub

This example adds a foreign key to the Orders table. The foreign key is based on the EmployeeID field and refers to the EmployeeID field of the Employees table. In this example, you don't have to list the EmployeeID field after the Employees table in the REFERENCES clause because EmployeeID is the primary key of the Employees table.

Sub AlterTableX3()

   Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Add a foreign key to the Orders table.
   dbs.Execute "ALTER TABLE Orders " _
      & "ADD CONSTRAINT OrdersRelationship " _
      & "FOREIGN KEY (EmployeeID) " _
      & "REFERENCES Employees (EmployeeID);"

   dbs.Close

End Sub

This example removes the foreign key from the Orders table.

Sub AlterTableX4()

   Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Remove the OrdersRelationship foreign key from
   ' the Orders table.
   dbs.Execute "ALTER TABLE Orders " _
      & "DROP CONSTRAINT OrdersRelationship;"

   dbs.Close

End Sub


CREATE INDEX Statement Example (DAO)

CREATE INDEX Statement Example

This example creates an index consisting of the fields Home Phone and Extension in the Employees table.

Sub CreateIndexX1()

   Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Create the NewIndex index on the Employees table.
   dbs.Execute "CREATE INDEX NewIndex ON Employees " _
      & "(HomePhone, Extension);"

   dbs.Close

End Sub

This example creates an index on the Customers table using the CustomerID field. No two records can have the same data in the CustomerID field, and no Null values are allowed.

Sub CreateIndexX2()

   Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Create a unique index, CustID, on the
   ' CustomerID field.
   dbs.Execute "CREATE UNIQUE INDEX CustID " _
      & "ON Customers (CustomerID) " _
      & "WITH DISALLOW NULL;"

   dbs.Close

End Sub


CREATE TABLE Statement, CONSTRAINT Clause Example (DAO)

CREATE TABLE Statement, CONSTRAINT Clause Example

This example creates a new table called ThisTable with two Text fields.

Sub CreateTableX1()

   Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

' Create a table with two text fields.
   dbs.Execute "CREATE TABLE ThisTable " _
      & "(FirstName TEXT, LastName TEXT);"

   dbs.Close

End Sub

This example creates a new table called MyTable with two Text fields, a Date/Time field, and a unique index made up of all three fields.

Sub CreateTableX2()

   Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Create a table with three fields and a unique
   ' index made up of all three fields.
   dbs.Execute "CREATE TABLE MyTable " _
      & "(FirstName TEXT, LastName TEXT, " _
      & "DateOfBirth DATETIME, " _
      & "CONSTRAINT MyTableConstraint UNIQUE " _
      & "(FirstName, LastName, DateOfBirth));"

   dbs.Close

End Sub

This example creates a new table with two Text fields and an Integer field. The SSN field is the primary key.

Sub CreateTableX3()

    Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Create a table with three fields and a primary
   ' key.
   dbs.Execute "CREATE TABLE NewTable " _
      & "(FirstName TEXT, LastName TEXT, " _
      & "SSN INTEGER CONSTRAINT MyFieldConstraint " _
      & "PRIMARY KEY);"

   dbs.Close

End Sub


DELETE Statement Example (DAO)

DELETE Statement Example

This example deletes all records for employees whose title is Trainee. When the FROM clause includes only one table, you don't have to list the table name in the DELETE statement.

Sub DeleteX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Delete employee records where title is Trainee.
   dbs.Execute "DELETE * FROM " _
      & "Employees WHERE Title = 'Trainee';"

   dbs.Close

End Sub


DROP Statement Example (DAO)

DROP Statement Example

The following example assumes the existence of a hypothetical NewIndex index on the Employees table in the Northwind database.

This example deletes the index MyIndex from the Employees table.

Sub DropX1()

   Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Delete NewIndex from the Employees table.
   dbs.Execute "DROP INDEX NewIndex ON Employees;"

   dbs.Close

End Sub

This example deletes the Employees table from the database.

Sub DropX2()

   Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Delete the Employees table.
   dbs.Execute "DROP TABLE Employees;"

   dbs.Close

End Sub


INSERT INTO Statement Example (DAO)

INSERT INTO Statement Example

This example selects all records in a hypothetical New Customers table and adds them to the Customers table. When individual columns are not designated, the SELECT table column names must match exactly those in the INSERT INTO table.

Sub InsertIntoX1()

   Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Select all records in the New Customers table
   ' and add them to the Customers table.
   dbs.Execute " INSERT INTO Customers " _
      & "SELECT * " _
      & "FROM [New Customers];"

   dbs.Close

End Sub

This example creates a new record in the Employees table.

Sub InsertIntoX2()

   Dim dbs As Database

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Create a new record in the Employees table. The
   ' first name is Harry, the last name is Washington,
   ' and the job title is Trainee.
   dbs.Execute " INSERT INTO Employees " _
      & "(FirstName,LastName, Title) VALUES " _
      & "('Harry', 'Washington', 'Trainee');"

   dbs.Close

End Sub


PARAMETERS Declaration Example (DAO)

PARAMETERS Declaration Example

This example requires the user to provide a job title and then uses that job title as the criteria for the query.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub ParametersX()

   Dim dbs As Database, qdf As QueryDef
   Dim rst As Recordset
   Dim strSql As String, strParm As String
   Dim strMessage As String
   Dim intCommand As Integer

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("NorthWind.mdb")

   ' Define the parameters clause.
   strParm = "PARAMETERS [Employee Title] TEXT; "

   ' Define an SQL statement with the parameters
   ' clause.
   strSql = strParm & "SELECT LastName, FirstName, " _
      & "EmployeeID " _
      & "FROM Employees " _
      & "WHERE Title =[Employee Title];"

   ' Create a QueryDef object based on the
   ' SQL statement.
   Set qdf = dbs.CreateQueryDef _
      ("Find Employees", strSql)

   Do While True
      strMessage = "Find Employees by Job " _
         & "title:" & Chr(13) _
         & "  Choose Job Title:" & Chr(13) _
         & " 1 - Sales Manager" & Chr(13) _
         & " 2 - Sales Representative" & Chr(13) _
         & " 3 - Inside Sales Coordinator"

      intCommand = Val(InputBox(strMessage))

      Select Case intCommand
         Case 1
            qdf("Employee Title") = _
               "Sales Manager"
         Case 2
            qdf("Employee Title") = _
               "Sales Representative"
         Case 3
            qdf("Employee Title") = _
               "Inside Sales Coordinator"
         Case Else
            Exit Do
      End Select

      ' Create a temporary snapshot-type Recordset.
      Set rst = qdf.OpenRecordset(dbOpenSnapshot)
      ' Populate the Recordset.
      rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
      EnumFields rst, 12
   Loop

   ' Delete the QueryDef because this is a
   ' demonstration.
   dbs.QueryDefs.Delete "Find Employees"

   dbs.Close

End Sub


PROCEDURE Clause Example (DAO)

PROCEDURE Clause Example

This example names the query CategoryList.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub ProcedureX()

   Dim dbs As Database, rst As Recordset
   Dim qdf As QueryDef, strSql As String

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   strSql = "PROCEDURE CategoryList; " _
      & "SELECT DISTINCTROW CategoryName, " _
      & "CategoryID FROM Categories " _
      & "ORDER BY CategoryName;"

   ' Create a named QueryDef based on the SQL
   ' statement.
   Set qdf = dbs.CreateQueryDef("NewQry", strSql)

   ' Create a temporary snapshot-type Recordset.
   Set rst = qdf.OpenRecordset(dbOpenSnapshot)
   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 15

   ' Delete the QueryDef because this is a
   ' demonstration.
   dbs.QueryDefs.Delete "NewQry"

   dbs.Close

End Sub


SELECT Statement, FROM Clause Example (DAO)

SELECT Statement, FROM Clause Example

Some of the following examples assume the existence of a hypothetical Salary field in an Employees table. Note that this field does not actually exist in the Northwind database Employees table.

This example creates a dynaset-type Recordset based on an SQL statement that selects the LastName and FirstName fields of all records in the Employees table. It calls the EnumFields procedure, which prints the contents of a Recordset object to the Debug window.

Sub SelectX1()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Select the last name and first name values of all
   ' records in the Employees table.
   Set rst = dbs.OpenRecordset("SELECT LastName, " _
      & "FirstName FROM Employees;")

   ' Populate the recordset.
   rst.MoveLast

' Call EnumFields to print the contents of the

' Recordset.

EnumFields rst,12

dbs.Close

End Sub

This example counts the number of records that have an entry in the PostalCode field and names the returned field Tally.

Sub SelectX2()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Count the number of records with a PostalCode
   ' value and return the total in the Tally field.
   Set rst = dbs.OpenRecordset("SELECT Count " _
      & "(PostalCode) AS Tally FROM Customers;")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of
   ' the Recordset. Specify field width = 12.
   EnumFields rst, 12

   dbs.Close

End Sub

This example shows the number of employees and the average and maximum salaries.

Sub SelectX3()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
Set dbs = OpenDatabase("Northwind.mdb")

   ' Count the number of employees, calculate the
   ' average salary, and return the highest salary.
   Set rst = dbs.OpenRecordset("SELECT Count (*) " _
      & "AS TotalEmployees, Avg(Salary) " _
      & "AS AverageSalary, Max(Salary) " _
      & "AS MaximumSalary FROM Employees;")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of
   ' the Recordset. Pass the Recordset object and
   ' desired field width.
   EnumFields rst, 17

   dbs.Close

End Sub

The Sub procedure EnumFields is passed a Recordset object from the calling procedure. The procedure then formats and prints the fields of the Recordset to the Debug window. The intFldLen variable is the desired printed field width. Some fields may be truncated.

Sub EnumFields(rst As Recordset, intFldLen As Integer)

   Dim lngRecords As Long, lngFields As Long
   Dim lngRecCount As Long, lngFldCount As Long
   Dim strTitle As String, strTemp As String

   ' Set the lngRecords variable to the number of
   ' records in the Recordset.
   lngRecords = rst.RecordCount
   ' Set the lngFields variable to the number of
   ' fields in the Recordset.
   lngFields = rst.Fields.Count

   Debug.Print "There are " & lngRecords _
      & " records containing " & lngFields _
      & " fields in the recordset."
   Debug.Print

   ' Form a string to print the column heading.
   strTitle = "Record  "
   For lngFldCount = 0 To lngFields - 1
      strTitle = strTitle _
      & Left(rst.Fields(lngFldCount).Name _
      & Space(intFldLen), intFldLen)
   Next lngFldCount

   ' Print the column heading.
   Debug.Print strTitle
   Debug.Print

   ' Loop through the Recordset; print the record
   ' number and field values.
   rst.MoveFirst
   For lngRecCount = 0 To lngRecords - 1
      Debug.Print Right(Space(6) & _
         Str(lngRecCount), 6) & "  ";
      For lngFldCount = 0 To lngFields - 1
         ' Check for Null values.
         If IsNull(rst.Fields(lngFldCount)) Then
            strTemp = "<null>"
         Else
            ' Set strTemp to the field contents.
            Select Case _
               rst.Fields(lngFldCount).Type
               Case 11
                  strTemp = ""
               Case dbText, dbMemo
                  strTemp = _
                     rst.Fields(lngFldCount)
               Case Else
                  strTemp = _
                     str(rst.Fields(lngFldCount))
            End Select
         End If
         Debug.Print Left(strTemp _
            & Space(intFldLen), intFldLen);
      Next lngFldCount
      Debug.Print
      rst.MoveNext
   Next lngRecCount

End Sub


SELECT...INTO Statement Example (DAO)

SELECT...INTO Statement Example

This example selects all records in the Employees table and copies them into a new table named Emp Backup.

Sub SelectIntoX()

   Dim dbs As Database
   Dim qdf As QueryDef

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Select all records in the Employees table
   ' and copy them into a new table, Emp Backup.
   dbs.Execute "SELECT Employees.* INTO " _
      & "[Emp Backup] FROM Employees;"

   ' Delete the table because this is a demonstration.
   dbs.Execute "DROP TABLE [Emp Backup];"

   dbs.Close

End Sub


ALL, DISTINCT, DISTINCTROW, TOP Predicates Example (DAO)

ALL, DISTINCT, DISTINCTROW, TOP Predicates Example

This example creates a query that joins the Customers and Orders tables on the CustomerID field. The Customers table contains no duplicate CustomerID fields, but the Orders table does because each customer can have many orders. Using DISTINCTROW produces a list of companies that have at least one order but without any details about those orders.

Sub AllDistinctX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Join the Customers and Orders tables on the
   ' CustomerID field. Select a list of companies
   ' that have at least one order.
   Set rst = dbs.OpenRecordset("SELECT DISTINCTROW " _
      & "CompanyName FROM Customers " _
      & "INNER JOIN Orders " _
      & "ON Customers.CustomerID = " _
      & "Orders.CustomerID " _
      & "ORDER BY CompanyName;")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 25

   dbs.Close

End Sub


GROUP BY Clause Example (DAO)

GROUP BY Clause Example

This example creates a list of unique job titles and the number of employees with each title.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub GroupByX1()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' For each title, count the number of employees
   ' with that title.
   Set rst = dbs.OpenRecordset("SELECT Title, " _
      & "Count([Title]) AS Tally " _
      & "FROM Employees GROUP BY Title;")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 25

   dbs.Close

End Sub

For each unique job title, this example calculates the number of employees in Washington who have that title.

Sub GroupByX2()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' For each title, count the number of employees
   ' with that title. Only include employees in the
   ' Washington region.
   Set rst = dbs.OpenRecordset("SELECT Title, " _
      & "Count(Title) AS Tally " _
      & "FROM Employees WHERE Region = 'WA' " _
      & "GROUP BY Title;")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 25

   dbs.Close

End Sub


HAVING Clause Example (DAO)

HAVING Clause Example

This example selects the job titles assigned to more than one employee in the Washington region.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub HavingX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Select the job titles assigned to more than one
   ' employee in the Washington region.
   Set rst = dbs.OpenRecordset("SELECT Title, " _
      & "Count(Title) as Total FROM Employees " _
      & "WHERE Region = 'WA' " _
      & "GROUP BY Title HAVING Count(Title) > 1;")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print recordset contents.
   EnumFields rst, 25

   dbs.Close

End Sub


IN Clause Example (DAO)

IN Clause Example

The following table shows how you can use the IN clause to retrieve data from an external database. In each example, assume the hypothetical Customers table is stored in an external database.

External database
SQL statement
Microsoft Jet database SELECT CustomerID
FROM Customers
IN OtherDB.mdb
WHERE CustomerID Like "A*";
dBASE III or IV.
To retrieve data from a dBASE III table, substitute "dBASE III;" for "dBASE IV;". 		SELECT CustomerID
FROM Customer
IN "C:\DBASE\DATA\SALES" "dBASE IV;"
WHERE CustomerID Like "A*";
dBASE III or IV using Database syntax. SELECT CustomerID
FROM Customer
IN "" [dBASE IV; Database=C:\DBASE\DATA\SALES;]
WHERE CustomerID Like "A*";
Paradox 3.x or 4.x.
To retrieve data from a Paradox version 3.x table, substitute "Paradox 3.x;" for "Paradox 4.x;". 		SELECT CustomerID
FROM Customer
IN "C:\PARADOX\DATA\SALES" "Paradox 4.x;"
WHERE CustomerID Like "A*";
Paradox 3.x or 4.x using Database syntax. SELECT CustomerID
FROM Customer
IN "" [Paradox 4.x;Database=C:\PARADOX\DATA\SALES;]
WHERE CustomerID Like "A*";
A Microsoft Excel worksheet SELECT CustomerID, CompanyName
FROM [Customers$]
IN "c:\documents\xldata.xls" "EXCEL 5.0;"
WHERE CustomerID Like "A*"
ORDER BY CustomerID;
A named range in a worksheet SELECT CustomerID, CompanyName
FROM CustomersRange
IN "c:\documents\xldata.xls" "EXCEL 5.0;"
WHERE CustomerID Like "A*"
ORDER BY CustomerID;


In Operator Example (DAO)

In Operator Example

The following example uses the Orders table in the Northwind.mdb database to create a query that includes all orders shipped to Lancashire and Essex and the dates shipped.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub InX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Select records from the Orders table that
   ' have a ShipRegion value of Lancashire or Essex.
   Set rst = dbs.OpenRecordset("SELECT " _
      & "CustomerID, ShippedDate FROM Orders " _
      & "WHERE ShipRegion In " _
      & "('Lancashire','Essex');")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of
   ' the Recordset.
   EnumFields rst, 12

   dbs.Close

End Sub


INNER JOIN Operation Example (DAO)

INNER JOIN Operation Example

This example creates two equi-joins: one between the Order Details and Orders tables and another between the Orders and Employees tables. This is necessary because the Employees table doesn't contain sales data, and the Order Details table doesn't contain employee data. The query produces a list of employees and their total sales.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub InnerJoinX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Create a join between the Order Details and
   ' Orders tables and another between the Orders and
   ' Employees tables. Get a list of employees and
   ' their total sales.
   Set rst = dbs.OpenRecordset("SELECT DISTINCTROW " _
      & "Sum(UnitPrice * Quantity) AS Sales, " _
      & "(FirstName & Chr(32) & LastName) AS Name " _
      & "FROM Employees INNER JOIN(Orders " _
      & "INNER JOIN [Order Details] " _
      & "ON [Order Details].OrderID = " _
      & "Orders.OrderID ) " _
      & "ON Orders.EmployeeID = " _
      & "Employees.EmployeeID " _
      & "GROUP BY (FirstName & Chr(32) & LastName);")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 20

   dbs.Close

End Sub


LEFT JOIN, RIGHT JOIN Operations Example (DAO)

LEFT JOIN, RIGHT JOIN Operations Example

This example assumes the existence of hypothetical Department Name and Department ID fields in an Employees table. Note that these fields do not actually exist in the Northwind database Employees table.

This example selects all departments, including those without employees.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub LeftRightJoinX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Select all departments, including those
   ' without employees.
   Set rst = dbs.OpenRecordset _
      ("SELECT [Department Name], " _
      & "FirstName & Chr(32) & LastName AS Name " _
      & "FROM Departments LEFT JOIN Employees " _
      & "ON Departments.[Department ID] = " _
      & "Employees.[Department ID] " _
      & "ORDER BY [Department Name];")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 20

   dbs.Close

End Sub


ORDER BY Clause Example (DAO)

ORDER BY Clause Example

The SQL statement shown in the following example uses the ORDER BY clause to sort records by last name in descending order (Z-A).

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub OrderByX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Select the last name and first name values from
   ' the Employees table, and sort them in descending
   ' order.
   Set rst = dbs.OpenRecordset("SELECT LastName, " _
      & "FirstName FROM Employees " _
      & "ORDER BY LastName DESC;")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print recordset contents.
   EnumFields rst, 12

   dbs.Close

End Sub


SQL Subqueries Example (DAO)

SQL Subqueries Example

This example lists the name and contact of every customer who placed an order in the second quarter of 1995.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub SubQueryX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' List the name and contact of every customer
   ' who placed an order in the second quarter of
   ' 1995.
   Set rst = dbs.OpenRecordset("SELECT ContactName," _
      & " CompanyName, ContactTitle, Phone" _
      & " FROM Customers" _
      & " WHERE CustomerID" _
      & " IN (SELECT CustomerID FROM Orders" _
      & " WHERE OrderDate Between #04/1/95#" _
      & " And #07/1/95#);")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 25

   dbs.Close

End Sub


TRANSFORM Statement Example (DAO)

TRANSFORM Statement Example

This example uses the SQL TRANSFORM clause to create a crosstab query showing the number of orders taken by each employee for each calendar quarter of 1994. The SQLTRANSFORMOutput function is required for this procedure to run.

Sub TransformX1()

   Dim dbs As Database
   Dim strSQL As String
   Dim qdfTRANSFORM As QueryDef

   strSQL = "PARAMETERS prmYear SHORT; TRANSFORM " _
      & "Count(OrderID) " _
      & "SELECT FirstName & "" "" & LastName AS " _
      & "FullName FROM Employees INNER JOIN Orders " _
      & "ON Employees.EmployeeID = " _
      & "Orders.EmployeeID WHERE DatePart " _
      & "(""yyyy"", OrderDate) = [prmYear] "

    strSQL = strSQL & "GROUP BY FirstName & " _
      & """ "" & LastName " _
      & "ORDER BY FirstName & "" "" & LastName " _
      & "PIVOT DatePart(""q"", OrderDate)"

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   Set qdfTRANSFORM = dbs.CreateQueryDef _
      ("", strSQL)

   SQLTRANSFORMOutput qdfTRANSFORM, 1994

   dbs.Close

End Sub

This example uses the SQL TRANSFORM clause to create a slightly more complex crosstab query showing the total dollar amount of orders taken by each employee for each calendar quarter of 1994. The SQLTRANSFORMOutput function is required for this procedure to run.

Sub TransformX2()

   Dim dbs As Database
   Dim strSQL As String
   Dim qdfTRANSFORM As QueryDef

   strSQL = "PARAMETERS prmYear SHORT; TRANSFORM " _
      & "Sum(Subtotal) SELECT FirstName & "" """ _
      & "& LastName AS FullName " _
      & "FROM Employees INNER JOIN " _
      & "(Orders INNER JOIN [Order Subtotals] " _
      & "ON Orders.OrderID = " _
      & "[Order Subtotals].OrderID) " _
      & "ON Employees.EmployeeID = " _
      & "Orders.EmployeeID WHERE DatePart" _
      & "(""yyyy"", OrderDate) = [prmYear] "

    strSQL = strSQL & "GROUP BY FirstName & "" """ _
      & "& LastName " _
      & "ORDER BY FirstName & "" "" & LastName " _
      & "PIVOT DatePart(""q"",OrderDate)"

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   Set qdfTRANSFORM = dbs.CreateQueryDef _
      ("", strSQL)

   SQLTRANSFORMOutput qdfTRANSFORM, 1994

   dbs.Close

End Sub

Function SQLTRANSFORMOutput(qdfTemp As QueryDef, _
   intYear As Integer)

   Dim rstTRANSFORM As Recordset
   Dim fldLoop As Field
   Dim booFirst As Boolean

   qdfTemp.PARAMETERS!prmYear = intYear
   Set rstTRANSFORM = qdfTemp.OpenRecordset()

   Debug.Print qdfTemp.SQL
   Debug.Print
   Debug.Print , , "Quarter"

   With rstTRANSFORM
      booFirst = True
      For Each fldLoop In .Fields
         If booFirst = True Then
            Debug.Print fldLoop.Name
            Debug.Print , ;
            booFirst = False
         Else
            Debug.Print , fldLoop.Name;
         End If
      Next fldLoop
      Debug.Print

      Do While Not .EOF
         booFirst = True
         For Each fldLoop In .Fields
            If booFirst = True Then
               Debug.Print fldLoop
               Debug.Print , ;
               booFirst = False
            Else
               Debug.Print , fldLoop;
            End If
         Next fldLoop
         Debug.Print
         .MoveNext
      Loop
   End With

End Function


UPDATE Statement Example (DAO)

UPDATE Statement Example

This example changes values in the ReportsTo field to 5 for all employee records that currently have ReportsTo values of 2.

Sub UpdateX()

   Dim dbs As Database
   Dim qdf As QueryDef

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Change values in the ReportsTo field to 5 for all
   ' employee records that currently have ReportsTo
   ' values of 2.
   dbs.Execute "UPDATE Employees " _
      & "SET ReportsTo = 5 " _
      & "WHERE ReportsTo = 2;"

   dbs.Close

End Sub


UNION Operation Example (DAO)

UNION Operation Example

This example retrieves the names and cities of all suppliers and customers in Brazil.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub UnionX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Retrieve the names and cities of all suppliers
   ' and customers in Brazil.
   Set rst = dbs.OpenRecordset("SELECT CompanyName," _
      & " City FROM Suppliers" _
      & " WHERE Country = 'Brazil' UNION" _
      & " SELECT CompanyName, City FROM Customers" _
      & " WHERE Country = 'Brazil';")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 12

   dbs.Close

End Sub


WHERE Clause Example (DAO)

WHERE Clause Example

The following example assumes the existence of a hypothetical Salary field in an Employees table. Note that this field does not actually exist in the Northwind database Employees table.

This example selects the LastName and FirstName fields of each record in which the last name is King.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub WhereX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Select records from the Employees table where the
   ' last name is King.
   Set rst = dbs.OpenRecordset("SELECT LastName, " _
      & "FirstName FROM Employees " _
      & "WHERE LastName = 'King';")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset.
   EnumFields rst, 12

   dbs.Close

End Sub


Avg Function Example (DAO)

Avg Function Example

This example uses the Orders table to calculate the average freight charges for orders with freight charges over $100.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub AvgX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Calculate the average freight charges for orders
   ' with freight charges over $100.
   Set rst = dbs.OpenRecordset("SELECT Avg(Freight)" _
      & " AS [Average Freight]" _
      & " FROM Orders WHERE Freight > 100;")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 25

   dbs.Close

End Sub


Count Function Example (DAO)

Count Function Example

This example uses the Orders table to calculate the number of orders shipped to the United Kingdom.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub CountX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Calculate the number of orders shipped
   ' to the United Kingdom.
   Set rst = dbs.OpenRecordset("SELECT" _
      & " Count (ShipCountry)" _
      & " AS [UK Orders] FROM Orders" _
      & " WHERE ShipCountry = 'UK';")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 25

   dbs.Close

End Sub


First, Last Functions Example (DAO)

First, Last Functions Example

This example uses the Employees table to return the values from the LastName field of the first and last records returned from the table.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub FirstLastX1()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Return the values from the LastName field of the
   ' first and last records returned from the table.
   Set rst = dbs.OpenRecordset("SELECT " _
      & "First(LastName) as First, " _
      & "Last(LastName) as Last FROM Employees;")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 12

   dbs.Close

End Sub

The next example compares using the First and Last functions with simply using the Min and Max functions to find the earliest and latest birth dates of Employees.

Sub FirstLastX2()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Find the earliest and latest birth dates of
   ' Employees.
   Set rst = dbs.OpenRecordset("SELECT " _
      & "First(BirthDate) as FirstBD, " _
      & "Last(BirthDate) as LastBD FROM Employees;")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 12

   Debug.Print

   ' Find the earliest and latest birth dates of
   ' Employees.
   Set rst = dbs.OpenRecordset("SELECT " _
      & "Min(BirthDate) as MinBD," _
      & "Max(BirthDate) as MaxBD FROM Employees;")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 12

   dbs.Close

End Sub


Min, Max Functions Example (DAO)

Min, Max Functions Example

This example uses the Orders table to return the lowest and highest freight charges for orders shipped to the United Kingdom.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub MinMaxX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Return the lowest and highest freight charges for
   ' orders shipped to the United Kingdom.
   Set rst = dbs.OpenRecordset("SELECT " _
      & "Min(Freight) AS [Low Freight], " _
      & "Max(Freight)AS [High Freight] " _
      & "FROM Orders WHERE ShipCountry = 'UK';")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 12

   dbs.Close

End Sub


StDev, StDevP Functions Example (DAO)

StDev, StDevP Functions Example

This example uses the Orders table to estimate the standard deviation of the freight charges for orders shipped to the United Kingdom.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub StDevX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Calculate the standard deviation of the freight
   ' charges for orders shipped to the United Kingdom.
   Set rst = dbs.OpenRecordset("SELECT " _
      & "StDev(Freight) " _
      & "AS [Freight Deviation] FROM Orders " _
      & "WHERE ShipCountry = 'UK';")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 15

   Debug.Print

   Set rst = dbs.OpenRecordset("SELECT " _
      & "StDevP(Freight) " _
      & "AS [Freight DevP] FROM Orders " _
      & "WHERE ShipCountry = 'UK';")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 15

   dbs.Close

End Sub


Sum Function Example (DAO)

Sum Function Example

This example uses the Orders table to calculate the total sales for orders shipped to the United Kingdom.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub SumX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Calculate the total sales for orders shipped to
   ' the United Kingdom.
   Set rst = dbs.OpenRecordset("SELECT" _
      & " Sum(UnitPrice*Quantity)" _
      & " AS [Total UK Sales] FROM Orders" _
      & " INNER JOIN [Order Details] ON" _
      & " Orders.OrderID = [Order Details].OrderID" _
      & " WHERE (ShipCountry = 'UK');")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 15

   dbs.Close

End Sub


Var, VarP Functions Example (DAO)

Var, VarP Functions Example

This example uses the Orders table to estimate the variance of freight costs for orders shipped to the United Kingdom.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub VarX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Calculate the variance of freight costs for
   ' orders shipped to the United Kingdom.
   Set rst = dbs.OpenRecordset("SELECT " _
      & "Var(Freight) " _
      & "AS [UK Freight Variance] " _
      & "FROM Orders WHERE ShipCountry = 'UK';")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 20

   Debug.Print

   Set rst = dbs.OpenRecordset("SELECT " _
      & "VarP(Freight) " _
      & "AS [UK Freight VarianceP] " _
      & "FROM Orders WHERE ShipCountry = 'UK';")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 20

   dbs.Close

End Sub


Like Operator Example (DAO)

Like Operator Example

This example returns a list of employees whose names begin with the letters A through D.

This example calls the EnumFields procedure, which you can find in the SELECT statement example.

Sub LikeX()

   Dim dbs As Database, rst As Recordset

   ' Modify this line to include the path to Northwind
   ' on your computer.
   Set dbs = OpenDatabase("Northwind.mdb")

   ' Return a list of employees whose names begin with
   ' the letters A through D.
   Set rst = dbs.OpenRecordset("SELECT LastName," _
      & " FirstName FROM Employees" _
      & " WHERE LastName Like '[A-D]*';")

   ' Populate the Recordset.
   rst.MoveLast

   ' Call EnumFields to print the contents of the
   ' Recordset. Pass the Recordset object and desired
   ' field width.
   EnumFields rst, 15

   dbs.Close

End Sub


Trappable Microsoft Jet and DAO Errors

Trappable errors from the Microsoft Jet database engine can occur while an application is running, either within the development environment or as a stand-alone executable file. You can test and respond to trappable errors using the Error object.

CodeMessage

2421Syntax error in date.

2422Syntax error in string.

2423Invalid use of '.', '!', or '()'.

2424Unknown name.

2425Unknown function name.

2426Function isn't available in expressions.

2427Object has no value.

2428Invalid arguments used with domain function.

2429In operator without ().

2430Between operator without And.

2431Syntax error (missing operator).

2432Syntax error (comma).

2433Syntax error.

2434Syntax error (missing operator).

2435Extra ).

2436Missing ), ], or Item.

2437Invalid use of vertical bars.

2438Syntax error.

2439Wrong number of arguments used with function.

2440IIf function without ().

2442Invalid use of parentheses.

2443Invalid use of Is operator.

2445Expression too complex.

2446Out of memory during calculation.

2447Invalid use of '.', '!', or '()'.

2448Can't set value.

3000Reserved error <Item>; there is no message for this error.

3001Invalid argument.

3002Couldn't start session.

3003Couldn't start transaction; too many transactions already nested.

3005<Database name> isn't a valid database name.

3006Database <name> is exclusively locked.

3007Can't open library database <name>.

3008The table <name> is already opened exclusively by another user, or it is already open through the user interface and cannot be manipulated programmatically.

3009You tried to lock table <table> while opening it, but the table can't be locked because it is currently in use. Wait a moment, and then try the operation again.

3010Table <name> already exists.

3011The Microsoft Jet database engine could not find the object <name>. Make sure the object exists and that you spell its name and the path name correctly.

3012Object <name> already exists.

3013Couldn't rename installable ISAM file.

3014Can't open any more tables.

3015<Index name> isn't an index in this table. Look in the Indexes collection of the TableDef object to determine the valid index names.

3016Field won't fit in record.

3017The size of a field is too long.

3018Couldn't find field <name>.

3019Operation invalid without a current index.

3020You tried to call Update or CancelUpdate or attempted to update a Field in a recordset without first calling AddNew or Edit.

3021No current record.

3022The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.

3023AddNew or Edit already used.

3024Couldn't find file <name>.

3025Can't open any more files.

3026Not enough space on disk.

3027Can't update. Database or object is read-only.

3028Can't start your application. The workgroup information file is missing or opened exclusively by another user.

3029Not a valid account name or password.

3030<Account name> isn't a valid account name.

3031Not a valid password.

3032Can't perform this operation.

3033You don't have the necessary permissions to use the <name> object. Have your system administrator or the person who created this object establish the appropriate permissions for you.

3034You tried to commit or roll back a transaction without first using BeginTrans.

3036Database has reached maximum size.

3037Can't open any more tables or queries.

3039Couldn't create index; too many indexes already defined.

3040Disk I/O error during read.

3041Can't open a database created with a previous version of your application.

3042Out of MS-DOS file handles.

3043Disk or network error.

3044<Path> isn't a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.

3045Couldn't use <name>; file already in use.

3046Couldn't save; currently locked by another user.

3047Record is too large.

3048Can't open any more databases.

3049Can't open database <name>. It may not be a database that your application recognizes, or the file may be corrupt.

3051The Microsoft Jet database engine cannot open the file <name>. It is already opened exclusively by another user, or you need permission to view its data.

3052File sharing lock count exceeded.

3053Too many client tasks.

3054Too many Memo or OLE Object fields.

3055Not a valid file name.

3056Couldn't repair this database.

3057Operation not supported on linked tables.

3058Index or primary key can't contain a Null value.

3059Operation canceled by user.

3060Wrong data type for parameter <parameter>.

3061Too few parameters. Expected <number>.

3062Duplicate output alias <name>.

3063Duplicate output destination <name>.

3064Can't open action query <name>.

3065Can't execute a select query.

3066Query must have at least one destination field.

3067Query input must contain at least one table or query.

3068Not a valid alias name.

3069The action query <name> cannot be used as a row source.

3070The Microsoft Jet database engine does not recognize <name> as a valid field name or expression.

3071This expression is typed incorrectly, or it is too complex to be evaluated. For example, a numeric expression may contain too many complicated elements. Try simplifying the expression by assigning parts of the expression to variables.

3073Operation must use an updatable query.

3074Can't repeat table name <name> in FROM clause.

3075<Message> in query expression <expression>.

3076<Name> in criteria expression.

3077<Message> in expression.

3078The Microsoft Jet database engine cannot find the input table or query <name>. Make sure it exists and that its name is spelled correctly.

3079The specified field <field> could refer to more than one table listed in the FROM clause of your SQL statement.

3080Joined table <name> not listed in FROM clause.

3081Can't join more than one table with the same name <name>.

3082JOIN operation <operation> refers to a field that isn't in one of the joined tables.

3083Can't use internal report query.

3084Can't insert data with action query.

3085Undefined function <name> in expression.

3086Couldn't delete from specified tables.

3087Too many expressions in GROUP BY clause.

3088Too many expressions in ORDER BY clause.

3089Too many expressions in DISTINCT output.

3090Resultant table not allowed to have more than one AutoNumber field.

3092Can't use HAVING clause in TRANSFORM statement.

3093ORDER BY clause <clause> conflicts with DISTINCT.

3094ORDER BY clause <clause> conflicts with GROUP BY clause.

3095Can't have aggregate function in expression <expression>.

3096Can't have aggregate function in WHERE clause <clause>.

3097Can't have aggregate function in ORDER BY clause <clause>.

3098Can't have aggregate function in GROUP BY clause <clause>.

3099Can't have aggregate function in JOIN operation <operation>.

3100Can't set field <name> in join key to Null.

3101The Microsoft Jet database engine can't find a record in the table <name> with key matching field(s) <name>.

3102Circular reference caused by <query reference>.

3103Circular reference caused by alias <name> in query definition's SELECT list.

3104Can't specify fixed column heading <value> in a crosstab query more than once.

3105Missing destination field name in SELECT INTO statement <statement>.

3106Missing destination field name in UPDATE statement <statement>.

3107Record(s) can't be added; no insert permission on <name>.

3108Record(s) can't be edited; no update permission on <name>.

3109Record(s) can't be deleted; no delete permission on <name>.

3110Couldn't read definitions; no read definitions permission for table or query <name>.

3111Couldn't create; no modify design permission for table or query <name>.

3112Record(s) can't be read; no read permission on <name>.

3113Can't update <field name>; field not updatable.

3114Can't include Memo or OLE Object when you select unique values <statement>.

3115Can't have Memo or OLE Object fields in aggregate argument <statement>.

3116Can't have Memo or OLE Object fields in criteria <criteria> for aggregate function.

3117Can't sort on Memo or OLE Object <clause>.

3118Can't join on Memo or OLE Object <name>.

3119Can't group on Memo or OLE Object <clause>.

3120Can't group on fields selected with '*' <table name>.

3121Can't group on fields selected with '*'.

3122You tried to execute a query that doesn't include the specified expression <name> as part of an aggregate function.

3123Can't use '*' in crosstab query.

3124Can't input from internal report query <name>.

3125The database engine can't find <name>. Make sure it is a valid parameter or alias name, that it doesn't include invalid characters or punctuation, and that the name isn't too long.

3126Invalid bracketing of name <name>.

3127The INSERT INTO statement contains the following unknown field name: <field name>. Make sure you've typed the name correctly, and try the operation again.

3128Specify the table containing the records you want to delete.

3129Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.

3130Syntax error in DELETE statement.

3131Syntax error in FROM clause.

3132Syntax error in GROUP BY clause.

3133Syntax error in HAVING clause.

3134Syntax error in INSERT INTO statement.

3135Syntax error in JOIN operation.

3136The LEVEL clause includes a reserved word or argument that is misspelled or missing, or the punctuation is incorrect.

3138Syntax error in ORDER BY clause.

3139Syntax error in PARAMETER clause.

3140Syntax error in PROCEDURE clause.

3141The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect.

3143Syntax error in TRANSFORM statement.

3144Syntax error in UPDATE statement.

3145Syntax error in WHERE clause.

3146ODBC – call failed.

3151ODBC – connection to <name> failed.

3154ODBC – couldn't find DLL <name>.

3155ODBC – insert on a linked table <table> failed.

3156ODBC – delete on a linked table <table> failed.

3157ODBC – update on a linked table <table> failed.

3158Couldn't save record; currently locked by another user.

3159Not a valid bookmark.

3160Table isn't open.

3161Couldn't decrypt file.

3162You tried to assign the Null value to a variable that isn't a Variant data type.

3163The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data.

3164The field can't be updated because another user or process has locked the corresponding record or table.

3165Couldn't open .inf file.

3166Cannot locate the requested Xbase memo file.

3167Record is deleted.

3168Invalid .inf file.

3169The Microsoft Jet database engine could not execute the SQL statement because it contains a field that has an invalid data type.

3170Couldn't find installable ISAM.

3171Couldn't find network path or user name.

3172Couldn't open Paradox.net.

3173Couldn't open table 'MSysAccounts' in the workgroup information file.

3174Couldn't open table 'MSysGroups' in the workgroup information file.

3175Date is out of range or is in an invalid format.

3176Couldn't open file <name>.

3177Not a valid table name.

3179Encountered unexpected end of file.

3180Couldn't write to file <name>.

3181Invalid range.

3182Invalid file format.

3183Not enough space on temporary disk.

3184Couldn't execute query; couldn't find linked table.

3185SELECT INTO on a remote database tried to produce too many fields.

3186Couldn't save; currently locked by user <name> on machine <name>.

3187Couldn't read; currently locked by user <name> on machine <name>.

3188Couldn't update; currently locked by another session on this machine.

3189Table <name> is exclusively locked by user <name> on machine <name>.

3190Too many fields defined.

3191Can't define field more than once.

3192Couldn't find output table <name>.

3196The database <database name> is already in use by another person or process. When the database is available, try the operation again.

3197The Microsoft Jet database engine stopped the process because you and another user are attempting to change the same data at the same time.

3198Couldn't start session. Too many sessions already active.

3199Couldn't find reference.

3200The record cannot be deleted or changed because table <name> includes related records.

3201You can't add or change a record because a related record is required in table <name>.

3202Couldn't save; currently locked by another user.

3203Subqueries cannot be used in the expression <expression>.

3204Database already exists.

3205Too many crosstab column headers <value>.

3206Can't create a relationship between a field and itself.

3207Operation not supported on a Paradox table with no primary key.

3208Invalid Deleted setting in the Xbase key of the Windows Registry.

3210The connection string is too long.

3211The database engine couldn't lock table <name> because it's already in use by another person or process.

3212Couldn't lock table <name>; currently in use by user <name> on machine <name>.

3213Invalid Date setting in the Xbase key of the Windows Registry.

3214Invalid Mark setting in the Xbase key of the Windows Registry.

3215Too many Btrieve tasks.

3216Parameter <name> specified where a table name is required.

3217Parameter <name> specified where a database name is required.

3218Couldn't update; currently locked.

3219Invalid operation.

3220Incorrect collating sequence.

3221Invalid settings in the Btrieve key of the Windows Registry.

3222Query can't contain a Database parameter.

3223<Parameter name> is invalid because it is too long or contains invalid characters.

3224Can't read Btrieve data dictionary.

3225Encountered a record locking deadlock while performing a Btrieve operation.

3226Errors encountered while using the Btrieve DLL.

3227Invalid Century setting in the Xbase key of the Windows Registry.

3228Selected collating sequence not supported by the operating system.

3229Btrieve–can't change field.

3230Out-of-date Paradox lock file.

3231ODBC–field would be too long; data truncated.

3232ODBC–couldn't create table.

3234ODBC–remote query timeout expired.

3235ODBC–data type not supported on server.

3238ODBC–data out of range.

3239Too many active users.

3240Btrieve–missing Btrieve engine.

3241Btrieve–out of resources.

3242Invalid reference in SELECT statement.

3243None of the import field names match fields in the appended table.

3244Can't import password-protected spreadsheet.

3245Couldn't parse field names from the first row of the import table.

3246Operation not supported in transactions.

3247ODBC – linked table definition has changed.

3248Invalid NetworkAccess setting in the Windows Registry.

3249Invalid PageTimeout setting in the Windows Registry.

3250Couldn't build key.

3251Operation is not supported for this type of object.

3252Can't open a form whose underlying query contains a user-defined function that attempts to set or get the form's RecordsetClone property.

3254ODBC – Can't lock all records.

3256Index file not found.

3257Syntax error in WITH OWNERACCESS OPTION declaration.

3258The SQL statement couldn't be executed because it contains ambiguous outer joins. To force one of the joins to be performed first, create a separate query that performs the first join and then include that query in your SQL statement.

3259Invalid field data type.

3260Couldn't update; currently locked by user <name> on machine <name>.

3261Table <name> is exclusively locked by user <name> on machine <name>.

3262Couldn't lock table <name>; currently in use by user <name> on machine <name>.

3263Invalid Database object.

3264No field defined – cannot append TableDef or Index.

3265Item not found in this collection.

3266.Can't append a Field that is already a part of a Fields collection.

3267Property can be set only when the Field is part of a Recordset object's Fields collection.

3268Can't set this property once the object is part of a collection.

3269Can't append an Index that is already a part of an Indexes collection.

3270Property not found.

3271Invalid property value.

3272Object isn't a collection.

3273Method not applicable for this object.

3274External table isn't in the expected format.

3275Unexpected error from external database driver <error number>.

3276Invalid database object reference.

3277Can't have more than 10 fields in an index.

3278The Microsoft Jet database engine has not been initialized.

3279The Microsoft Jet database engine has already been initialized.

3280Can't delete a field that is part of an index or is needed by the system.

3281Can't delete this index or table. It is either the current index or is used in a relationship.

3282Operation not supported on a table that contains data.

3283Primary key already exists.

3284Index already exists.

3285Invalid index definition.

3286Format of memo file doesn't match specified external database format.

3287Can't create index on the given field.

3288Paradox index is not primary.

3289Syntax error in CONSTRAINT clause.

3290Syntax error in CREATE TABLE statement.

3291Syntax error in CREATE INDEX statement.

3292Syntax error in field definition.

3293Syntax error in ALTER TABLE statement.

3294Syntax error in DROP INDEX statement.

3295Syntax error in DROP TABLE or DROP INDEX.

3296Join expression not supported.

3297Couldn't import table or query. No records found, or all records contain errors.

3298There are several tables with that name. Please specify owner in the format 'owner.table'.

3299ODBC Specification Conformance Error <message>. Report this error to the developer of your application.

3300Can't create a relationship.

3301Can't perform this operation; features in this version are not available in databases with older formats.

3302Can't change a rule while the rules for this table are in use.

3303Can't delete this field. It's part of one or more relationships.

3304You must enter a personal identifier (PID) consisting of at least 4 and no more than 20 characters and digits.

3305Invalid connection string in pass-through query.

3306You've written a subquery that can return more than one field without using the EXISTS reserved word in the main query's FROM clause. Revise the SELECT statement of the subquery to request only one field.

3307The number of columns in the two selected tables or queries of a union query don't match.

3308Invalid TOP argument in select query.

3309Property setting can't be larger than 2K.

3310This property isn't supported for external data sources or for databases created with a previous version of Microsoft Jet.

3311Property specified already exists.

3312Validation rules and default values can't be placed on system or linked tables.

3313Can't place this validation expression on this field.

3314The field <name> can't contain a Null value because the Required property for this field is set to True. Enter a value in this field.

3315Field <name> can't be a zero-length string.

3316<Table-level validation text>.

3317One or more values are prohibited by the validation rule <rule> set for <name>. Enter a value that the expression for this field can accept.

3318Values specified in a TOP clause are not allowed in delete queries or reports.

3319Syntax error in union query.

3320<Error> in table-level validation expression.

3321No database specified in connection string or IN clause.

3322Crosstab query contains one or more invalid fixed column headings.

3323The query cannot be used as a row source.

3324The query is a DDL query and cannot be used as a row source.

3325Pass-through query with ReturnsRecords property set to True did not return any records.

3326This Recordset is not updatable.

3334Can be present only in version 1.0 format.

3336Btrieve: Invalid IndexDDF option in initialization setting.

3337Invalid DataCodePage option in initialization setting.

3338Btrieve: Xtrieve options aren't correct in initialization setting.

3339Btrieve: Invalid IndexDeleteRenumber option in initialization setting.

3340Query <name> is corrupt.

3341The current field must match the join key <name> in the table that serves as the 'one' side of one-to-many relationship. Enter a record in the 'one' side table with the desired key value, and then make the entry with the desired join key in the 'many-only' table.

3342Invalid Memo or OLE Object in subquery <name>.

3343Unrecognized database format <filename>.

3344The database engine does not recognize either the field <name> in a validation expression, or the default value in the table <name>.

3345Unknown or invalid field reference <name>.

3346Number of query values and destination fields aren't the same.

3349Numeric field overflow.

3350Object is invalid for operation.

3351The ORDER BY expression <expression> includes fields that aren't selected by the query. Only those fields requested in the first query can be included in an ORDER BY expression.

3352No destination field name in INSERT INTO statement <statement>.

3353Btrieve: Can't find file Field.ddf.

3354At most one record can be returned by this subquery.

3355Syntax error in default value.

3356You attempted to open a database that is already opened exclusively by user <name> on machine <name>. Try again when the database is available.

3357This query is not a properly formed data-definition query.

3358Can't open the Microsoft Jet engine workgroup information file.

3359Pass-through query must contain at least one character.

3360Query is too complex.

3361Unions not allowed in a subquery.

3362Single-row update/delete affected more than one row of a linked table. Unique index contains duplicate values.

3364Can't use Memo or OLE Object field <name> in the SELECT clause of a union query.

3365Can't set this property for remote objects.

3366Can't append a relation with no fields defined.

3367Can't append. An object with that name already exists in the collection.

3368Relationship must be on the same number of fields with the same data types.

3370Can't modify the design of table <name>. It's in a read-only database.

3371Can't find table or constraint.

3372No such index <name> on table <name>.

3373Can't create relationship. Referenced table <name> doesn't have a primary key.

3374The specified fields are not uniquely indexed in table <name>.

3375Table <name> already has an index named <name>.

3376Table <name> doesn't exist.

3377No such relationship <name> on table <name>.

3378There is already a relationship named <name> in the current database.

3379Can't create relationships to enforce referential integrity. Existing data in table <name> violates referential integrity rules in table <name>.

3380Field <name> already exists in table <name>.

3381There is no field named <name> in table <name>.

3382Size of field <name> is too long.

3383Can't delete field <name>. It's part of one or more relationships.

3384Can't delete a built-in property.

3385User-defined properties don't support a Null value.

3386Property <name> must be set before using this method.

3388Unknown function <name> in validation expression or default value on <name>.

3389Query support unavailable.

3390Account name already exists.

3393Can't perform join, group, sort, or indexed restriction. A value being searched or sorted on is too long.

3394Can't save property; property is a schema property.

3396Can't perform cascading operation. Since related records exist in table <name>, referential integrity rules would be violated.

3397Can't perform cascading operation. There must be a related record in table <name>.

3398Can't perform cascading operation. It would result in a null key in table <name>.

3399Can't perform cascading operation. It would result in a duplicate key in table <name>.

3400Can't perform cascading operation. It would result in two updates to field <name> in table <name>.

3401Can't perform cascading operation. It would cause field <name> to become Null, which is not allowed.

3402Can't perform cascading operation. It would cause field <name> to become a zero-length string, which is not allowed.

3403Can't perform cascading operation: <validation text>.

3404Can't perform cascading operation. The value entered is prohibited by the validation rule <rule> set for <name>.

3405Error <error text> in validation rule.

3406The expression you're trying to use for the DefaultValue property is invalid because <error text>. Use a valid expression to set this property.

3407The server's MSysConf table exists, but is in an incorrect format. Contact your system administrator.

3409Invalid field definition <name> in definition of index or relationship.

3411Invalid entry. Can't perform cascading operation in table <name> because the value entered is too large for field <name>.

3412Can't perform cascading update on the table because it is currently in use by another user.

3414Can't perform cascading operation on table <name> because it is currently in use.

3415Zero-length string is valid only in a Text or Memo field.

3416<reserved error alert>

3417An action query cannot be used as a row source.

3418Can't open <tablename>. Another user has the table open using a different network control file or locking style.

3419Can't open this Paradox 4.x or 5.x table because ParadoxNetStyle is set to 3.x in the Windows Registry.

3420Object is invalid or no longer set.

3421Data type conversion error.

3422Can't modify table structure. Another user has the table open.

3423You cannot use ODBC to import from, export to, or link an external Microsoft Jet or ISAM database table to your database.

3424Can't create database because the locale is invalid.

3428A problem occurred in your database. Correct the problem by repairing and compacting the database.

3429Incompatible version of an installable ISAM.

3430While loading the Microsoft Excel installable ISAM, OLE was unable to initialize.

3431This is not a Microsoft Excel 5.0 file.

3432Error opening a Microsoft Excel 5.0 file.

3433Invalid setting in Excel key of the Engines section of the Windows Registry.

3434Can't expand named range.

3435Cannot delete spreadsheet cells.

3436Failure creating file.

3437Spreadsheet is full.

3438The data being exported does not match the format described in the Schema.ini file.

3439You attempted to link or import a Microsoft Word mail merge file. Although you can export such files, you cannot link or import them.

3440An attempt was made to import or link an empty text file. To import or link a text file, the file must contain data.

3441Text file specification field separator matches decimal separator or text delimiter.

3442In the text file specification <name>, the <name> option is invalid.

3443The fixed-width specification <name> contains no column widths.

3444In the fixed width specification <name>, column <column> does not specify a width.

3445Incorrect version of the DLL file <name> was found.

3446Jet VBA file (VBAJET.dll for 16-bit versions, or VBAJET32.dll for 32-bit versions) is missing. Try reinstalling the application that returned the error.

3447The Jet VBA file (VBAJET.dll for 16-bit versions, or VBAJET32.dll for 32-bit versions) failed to initialize when called. Try reinstalling the application that returned the error.

3448A call to an OLE system function was not successful. Try reinstalling the application that returned the error.

3449No country code found in the connection string.

3452You can't make changes to the design of the database at this replica.

3453You can't establish or maintain an enforced relationship between a replicated table and a local table.

3455Can't make the database replicable.

3456The object named <name> in the <name> collection cannot be made replicable.

3457You can't set the KeepLocal property for an object that is already replicated.

3458The KeepLocal property cannot be set on a database; it can be set only on the objects in a database.

3459After a database has been replicated, you cannot remove the replication features from the database.

3460The operation you attempted conflicts with an existing operation involving this member of the replica set.

3461The replication property you are attempting to set or delete is read-only and can't be changed.

3462Failure to load a DLL.

3463Can't find the .dll <name>.

3464Data type mismatch in criteria expression.

3465The disk drive you are attempting to access is unreadable.

3468Access was denied while accessing dropbox folder <name>.

3469The disk for dropbox folder <name> is full.

3470Disk failure accessing dropbox folder <name>.

3471Failure to write to the Synchronizer log file.

3472Disk full for path <name>.

3473Disk failure while accessing log file <name>.

3474Can't open the log file <name> for writing.

3475Sharing violation while attempting to open log file <name> in Deny Write mode.

3476Invalid dropbox path <name>.

3477Dropbox address <name> is syntactically invalid.

3478The replica is not a partial replica.

3479Can't designate a partial replica as the Design Master for the replica set.

3480The relationship <name> in the partial filter expression is invalid.

3481The table name <name> in the partial filter expression is invalid.

3482The filter expression for the partial replica is invalid.

3483The password supplied for the dropbox folder <name> is invalid.

3484The password used by the Synchronizer to write to a destination dropbox folder is invalid.

3485The object can't be replicated because the database is not replicated.

3486You can't add a second Replication ID AutoNumber field to a table.

3487The database you are attempting to replicate can't be converted.

3488The value specified is not a ReplicaID for any member in the replica set.

3489The object specified can't be replicated because it is missing a necessary resource.

3490Can't create a new replica because the <name> object in <name> container could not be replicated.

3491The database must be opened in exclusive mode before it can be replicated.

3492The synchronization failed because a design change could not be applied to one of the replicas.

3493Can't set the specified Registry parameter for the Synchronizer.

3494Unable to retrieve the specified Registry parameter for the Synchronizer.

3495There are no scheduled synchronizations between the two Synchronizers.

3496Replication Manager cannot find the ExchangeID in the MSysExchangeLog table.

3497Unable to set a schedule for the Synchronizer.

3499Can't retrieve the full path information for a member of the replica set.

3500You cannot specify two different Synchronizers to manage the same replica.

3502The Design Master or replica is not being managed by a Synchronizer.

3503The Synchronizer's Registry has no value set for the key you queried.

3504The Synchronizer ID does not match an existing ID in the MSysTranspAddress table.

3506The Synchronizer is unable to open the Synchronizer log.

3507Failure writing to the Synchronizer log.

3508There is no active transport for the Synchronizer.

3509Could not find a valid transport for this Synchronizer.

3510The member of the replica set you are attempting to synchronize is currently being used in another synchronization.

3512Failed to read the dropbox folder.

3513Failed to write to the dropbox folder.

3514Synchronizer could not find any scheduled or on-demand synchronizations to process.

3515The Microsoft Jet database engine could not read the system clock on your computer.

3516Could not find transport address.

3517Synchronizer could not find any messages to process.

3518Could not find Synchronizer in the MSysTranspAddress table.

3519Failed to send a message.

3520The replica name or ID does not match a currently managed member of the replica set.

3521Two members of the replica set cannot be synchronized because there is no common point to start the synchronization.

3522Synchronizer cannot find the record of a specific synchronization in the MSysExchangeLog table.

3523Synchronizer cannot find a specific version number in the MSysSchChange table.

3524The history of design changes in the replica does not match the history in the Design Master.

3525Synchronizer could not access the message database.

3526The name selected for the system object is already in use.

3527The Synchronizer or Replication Manager could not find the system object.

3528There is no new data in shared memory for the Synchronizer or Replication Manager to read.

3529The Synchronizer or Replication Manager found unread data in the shared memory. The existing data will be overwritten.

3530The Synchronizer is already serving a client.

3531The wait period for an event has timed out.

3532Synchronizer could not be initialized.

3533The system object used by a process still exists after the process has stopped.

3534Synchronizer looked for a system event but did not find one to report to the client.

3535Client has asked the Synchronizer to terminate operation.

3536Synchronizer received an invalid message for a member of the replica set that it manages.

3538Cannot initialize Synchronizer because there are too many applications running.

3539A system error has occurred or your swap file has reached its limit.

3540Your swap file has reached its limit or is corrupted.

3541Synchronizer could not be shut down properly and is still active.

3542Process stopped when attempting to terminate Synchronizer client.

3543Synchronizer has not been set up.

3544Synchronizer is already running.

3545The two replicas you are attempting to synchronize are from different replica sets.

3546The type of synchronization you are attempting is not valid.

3547Synchronizer could not find a replica from the correct set to complete the synchronization.

3548GUIDs do not match or the requested GUID could not be found.

3549The file name you provided is too long.

3550There is no index on the GUID column.

3551Unable to delete the specified Registry parameter for the Synchronizer.

3552The size of the Registry parameter exceeds the maximum allowed.

3553The GUID could not be created.

3555All valid nicknames for replicas are already in use.

3556Invalid path for destination dropbox folder.

3557Invalid address for destination dropbox folder.

3558Disk I/O error at destination dropbox folder.

3559Failure to write because destination disk is full.

3560The two members of the replica set you are attempting to synchronize have the same ReplicaID.

3561The two members of the replica set you are attempting to synchronize are both Design Masters.

3562Access denied at destination dropbox folder.

3563Fatal error accessing a local dropbox folder.

3564Synchronizer can't find the source file for messages.

3565There is a sharing violation in the source dropbox folder because the message database is open in another application.

3566Network I/O error.

3567Message in dropbox folder belongs to the wrong Synchronizer.

3568Synchronizer could not delete a file.

3569This member of the replica set has been logically removed from the set and is no longer available.

3571The attempt to set a column in a partial replica violated a rule governing partial replicas.

3572A disk I/O error occurred while reading or writing to the TEMP directory.

3574The ReplicaID for this member of the replica set was reassigned during a move or copy procedure.

3575The disk drive you are attempting to write to is full.

3576The database you are attempting to open is already in use by another application.

3577Can't update replication system column.

3578Failure to replicate database; can't determine whether the database is open in exclusive mode.

3581Can't open replication system table <name> because the table is already in use.

3583Cannot make the <name> object in <name> container replicable.

3584Insufficient memory to complete operation.

3586Syntax error in partial filter expression on table <name>.

3587Invalid expression in the ReplicaFilter property.

3588Error when evaluating the partial filter expression.

3589The partial filter expression contains an unknown function.

3592You can't replicate a password-protected database or set password protection on a replicated database.

3593You can't change the data master attribute for the replica set.

3594You can't change the data master attribute for the replica set. It allows data changes only at the Design Master.

3595The system tables in your replica are no longer reliable and the replica should not be used.

3605Synchronizing with a non-replicated database is not allowed. The <name> database is not a Design Master or replica.

3607The replication property you are attempting to delete is read-only and cannot be removed.

3608Record length is too long for an indexed Paradox table.

3609No unique index found for the referenced field of the primary table.

3610Same table <table> referenced as both the source and destination in a make-table query.

3611Can’t execute data definition statements on linked data sources.

3612Multi-level GROUP BY clause is not allowed in a subquery.

3613Can’t create a relationship on linked ODBC tables.

3614GUID not allowed in Find method criteria expression.

3615Type mismatch in JOIN expression.

3616Updating data in a linked table is not supported by this ISAM.

3617Deleting data in a linked table is not supported by this ISAM.

3618Exceptions table could not be created on import/export.

3619Records could not be added to exceptions table.

3620The connection for viewing your linked Microsoft Excel worksheet was lost.

3621Can’t change password on a shared open database.

3622You must use the dbSeeChanges option with OpenRecordset when accessing a SQL Server table that has an IDENTITY column.

3623Cannot access the FoxPro 3.0 bound DBF file <filename>.

3624Couldn’t read the record; currently locked by another user.

3625The text file specification <name> does not exist. You can’t import, export, or link using the specification.

3626The operation failed. There are too many indexes on table <name>. Delete some of the indexes on the table and try the operation again.

3627Cannot find the executable file for the Synchronizer (mstran35.exe).

3628Partner replica is not managed by a Synchronizer.

3629This Synchronizer and Synchronizer <name> have the same File System dropbox – <name>.

3631Invalid table name in filter.

3632Remote Synchronizer is not configured for remote synchronization.

3633Can't load DLL <name>.

3634Cannot create a replica using a partial replica.

3635Cannot create partial replica of a workgroup information file.

3636Cannot populate the replica or change the replica's filter because the replica has conflicts or data errors.

3637Cannot use the crosstab of a non-fixed column as a subquery.

3638You cannot make a database replicable that is being used by a program that controls modification.

3639Cannot create a replica of a workgroup information file.

3640The fetch buffer was too small for the amount of data you requested.

3641There are fewer records remaining in the Recordset than you requested.

3642A cancel was performed on the operation.

3643One of the records in the Recordset was deleted by another process.

3645One of the binding parameters is incorrect.

3646The specified row length is shorter than the sum of the column lengths.

3647A column requested is not being returned to the Recordset.

3648Cannot synchronize a partial replica with another partial replica.

3649The language-specific code page was not specified or could not be found.

3650Internet is too slow.

3651Invalid Internet address.

3652Internet login failure.

3653Internet not set up.

3656Error in evaluating a partial expression.

3660Requested exchange failed because <description>.


Syntax error in number. (Error 2420)

You entered a value that is invalid. This can occur if a nonnumeric value is provided as part of the expression.


Syntax error in date. (Error 2421)

Date syntax is incorrect. This error occurs if you specify an invalid date. For example, 9/31/94 is invalid (September has only 30 days).


Syntax error in string. (Error 2422)

You entered an expression that includes an invalid string. Check the expression to make sure you entered it correctly.


Invalid use of '.', '!', or '()'. (Error 2423)

The expression does not use delimiters correctly. To reference the properties of a DAO object, it is recommended that you use the .propertyname syntax.


Unknown name. (Error 2424)

You entered an expression that has a field or property name that cannot be recognized. Make sure the object exists, or check the expression to make sure you entered it correctly.


Unknown function name. (Error 2425)

You entered an expression with a function name that cannot be recognized. Make sure the function exists, or check the expression to make sure you entered it correctly.


Function isn't available in expressions. (Error 2426)

You have entered a function that cannot be used in this expression. The functions DoEvents, LBound, UBound, Spc, and Tab aren't available in expressions.


Object has no value. (Error 2427)

You entered an expression containing an identifier for an object that has no value. (Objects may have a default property value or return a default method.)

Check the expression to make sure you entered it correctly.


Invalid arguments used with domain function. (Error 2428)

You have entered an invalid argument in an aggregate function. For information on the function's arguments, see SQL Aggregate Functions, and then choose the name of the function.


In operator without (). (Error 2429)

When coding an SQL statement that includes the In operator, you must surround the list of items to test with parentheses. For example, to see if a value is one of a set of values, you could use the following code in the WHERE clause of an SQL query:

WHERE Region In ('TX', 'CA', 'WA')

This code tests to see if the Region field contains any of the above abbreviations, which represent Texas, California, and Washington.


Between operator without And. (Error 2430)

When using the Between operator to test whether a value of an expression lies within a specified range of values, specify the upper and lower limits of the range separated with the reserved word And. For example, to test for a range of A to C, you could use the following code:

WHERE fldName Between "A" And "C"


Syntax error (missing operator). (Error 2431)

The expression or statement is missing an operator.


Syntax error (comma). (Error 2432)

The expression or statement uses a comma where it does not belong or is missing a comma to separate arguments.


Syntax error. (Error 2433)

The wording or punctuation of the command is not correct. It may be missing an operator, or you may have specified an operator that does not exist.


Syntax error (missing operator). (Error 2434)

The expression or statement is missing an operator.


Extra ). (Error 2435)

You entered an expression that has too many closing parentheses. Delete any parenthesis that does not have a matching opening parenthesis.


Missing ), ], or Item. (Error 2436)

You entered an expression that is missing a closing parenthesis, bracket, or vertical bar. Check the expression to make sure you entered it correctly.


Invalid use of vertical bars. (Error 2437)

You entered an expression that has invalid vertical bars (|). Check the expression to make sure you entered it correctly.


Syntax error. (Error 2438)

You entered an expression that has invalid syntax. For example, an operand or operator may be missing, you may have entered an invalid character or comma, or you may have entered text without surrounding it by quotation marks ("). Check the expression to make sure you entered it correctly.


Wrong number of arguments used with function. (Error 2439)

You entered an expression that has a function with the wrong number of arguments. Check the function to verify how many arguments it takes, or check the expression to make sure you entered it correctly.


IIf function without (). (Error 2440)

The IIf function requires parentheses around its arguments, as shown in the following syntax:

IIf(expr, truepart, falsepart)


Invalid use of parentheses. (Error 2442)

You entered an expression that has invalid parentheses. For example, you may be trying to use the parentheses syntax for an identifier in a query. In a query, you can use only the standard identifier syntax.


Invalid use of Is operator. (Error 2443)

The Is operator is used to determine if an expression is Null. You can use the Is operator in an expression only with NULL or NOT NULL.


Expression too complex. (Error 2445)

This expression is too complex for the Microsoft Jet database engine. Try to simplify the expression.


Out of memory during calculation. (Error 2446)

The application does not have enough memory to complete the calculation. Make sure you have enough RAM and an established swap file. You may need to terminate other programs, remove desktop wallpaper bitmaps, or remove unneeded device drivers to recover enough memory.


Invalid use of '.', '!', or '()'. (Error 2447)

The expression does not use delimiters correctly. To reference the properties of DAO objects, use the .propertyname syntax.


Can't set value. (Error 2448)

You are trying to assign a value to an object that is read-only or does not have a value.


Reserved error <Item>; there is no message for this error. (Error 3000)

An unexpected error occurred. The specified code identifies the conditions under which this error can occur. Please contact Microsoft AnswerPoint for more information.


Invalid argument. (Error 3001)

You tried to perform an operation that involves a routine in a DLL, and one of the arguments to the routine is invalid. Check your entry to make sure you have specified the correct arguments, and then try the operation again.

This error also occurs when you attempt to use mutually exclusive constants in an argument to a method, such as specifying both dbConsistent and dbInconsistent in the options argument to the OpenRecordset method.


Couldn't start session. (Error 3002)

You tried to initiate an operation that requires a new session, but you have reached the limit of sessions that can be active at one time. Wait for other operations to finish or stop other operations, and then try the operation again.


Couldn't start transaction; too many transactions already nested. (Error 3003)

You tried to nest a transaction more than five levels deep. Use the CommitTrans or Rollback method to save or roll back the current transaction before you begin another one.


<Database name> isn't a valid database name. (Error 3005)

The specified database name does not follow the standard naming conventions for file names. The name may be too long for the buffer that contains the path and file name. Enter a new name, and then try the operation again.


Database <name> is exclusively locked. (Error 3006)

You tried to use a database that is currently open for exclusive access by another user. Wait for the other user to finish working with the database, and then try the operation again.


Can't open library database <name>. (Error 3007)

Can’t open library database <name>. (Error 3007)

The specified database is an internal Microsoft Jet database engine library database, which you cannot open.


The table <name> is already opened exclusively by another user, or it is already open through the user interface and cannot be manipulated programmatically. (Error 3008)

You tried to use a table that is currently open for exclusive access by another user, or you tried to programmatically manipulate a table that is open through the user interface. Address the appropriate condition, and then try the operation again.


You tried to lock table <table> while opening it, but the table can't be locked because it is currently in use. Wait a moment, and then try the operation again. (Error 3009)


Table <name> already exists. (Error 3010)

You tried to create or rename a table with a name that already exists in this database. Choose another name, and then try the operation again.

In a multiuser database, this error can also occur if you delete a table, another user creates a table with the same name, and then you try to roll back the deletion of your table. To restore your table, the other user must first delete or rename the new table before you try the rollback operation again.


The Microsoft Jet database engine could not find the object <name>. Make sure the object exists and that you spell its name and the path name correctly. (Error 3011)

Possible causes:

  • The specified object does not exist.

  • You misspelled the object name. Check for missing underscores ( _ ) or other punctuation, and make sure you did not enter leading spaces.

  • If you are trying to open a Btrieve table, the paths indicated in the data definition file File.ddf may be incorrect. Be sure your data (.dat) files are in the correct directories.


Object <name> already exists. (Error 3012)

You tried to create an object with a name that already exists in this database. Choose a different name, and then try the operation again.


Couldn't rename installable ISAM file. (Error 3013)

You tried to rename a Btrieve, dBASE, or Paradox table, but the file that contains that table could not be renamed.

Possible causes:

  • The file has been defined as read-only in the operating system or by your network.

  • In a network environment, you do not have write privileges for the file.


Can't open any more tables. (Error 3014)

You have reached the limit on the number of tables that can be opened at one time. Close one or more tables, and then try the operation again.


<Index name> isn't an index in this table. Look in the Indexes collection of the TableDef object to determine the valid index names. (Error 3015)

You tried to use a value that isn't an index. You can determine the valid index names by looking in the Indexes collection of the CdbTableDef object.


Field won't fit in record. (Error 3016)

You tried to import or paste a field that is too large. Consider breaking the field into smaller pieces and then importing or pasting the data to multiple fields or changing the data type of the field.

Records are limited to just under 2K in size, excluding Memo and OLE Object fields.


The size of a field is too long. (Error 3017)

Possible causes:

  • You tried to define or create a Text field longer than 254 characters. Use a number between 1 and 254, and then try the operation again, or create a Memo field for the data.

  • You tried to define a query parameter longer than 255 characters.


Couldn't find field <name>. (Error 3018)

Possible causes:

  • The specified field does not exist.

  • You misspelled the field name. Check for missing underscores ( _ ) or other punctuation, and make sure you did not enter leading spaces.

  • You entered an invalid field identifier. For example, [My Table]_[My Field] instead of MyTable![My Field].

  • You did not use brackets to surround a field name that contains spaces.


Operation invalid without a current index. (Error 3019)

Set the index, and then try the operation again.


You tried to call Update or CancelUpdate or attempted to update a Field in a recordset without first calling AddNew or Edit. (Error 3020)

On a Microsoft Jet database, you called the Update or CancelUpdate method but did not use the AddNew or Edit method before writing data to a record.

On an ODBCDirect database, this error occurs when you attempt to write data to a record without first calling AddNew or Edit.


No current record. (Error 3021)

This error occurs after the unsuccessful application of one of the Find methods or the Seek method, when the underlying CdbRecordset contains no records or the record has been deleted. Move to or select another record, and try the operation again. If the dbRecordset is empty, you cannot position to a current record. Check the BOF and EOF properties.


The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again. (Er

The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again. (Error 3022)

You tried to duplicate a value in a field that is the underlying table's primary key or an index that does not allow duplicates. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries, and try again.


AddNew or Edit already used. (Error 3023)

You have not saved or rolled back the current changes and are trying to add or change another record. Use the Rollback or Update method, and then use the AddNew or Edit method.


Couldn't find file <name>. (Error 3024)

Possible causes:

  • The specified file does not exist.

  • You misspelled the file name. Check for missing underscores ( _ ) or other punctuation, and make sure you didn't enter leading spaces.

  • The network connection has failed or has not been established.


Can't open any more files. (Error 3025)

You have reached the limit on the number of files that can be opened at one time. Close one or more files, and then try the operation again.


Not enough space on disk. (Error 3026)

You tried to perform an operation that requires more disk space than is available. Remove unused files from your disk, compress your database, and then try the operation again.


Can't update. Database or object is read-only. (Error 3027)

You tried to save changes in a database that was opened for read-only access.

The database is read-only for one of these reasons:

  • You used the OpenDatabase method and opened the database for read-only access.

  • The database file is defined as read-only in the operating system or by your network.

  • The database file is stored on read-only media.

  • In a network environment, you do not have write privileges for the database file.

  • When working with a secured database, the database or one of its objects (such as a field or table) may be set to read-only. You may not have permission to access this data with your user name and password.

Close the database, resolve the read-only condition, and then reopen the file for read/write access.


Can't start your application. The workgroup information file is missing or opened exclusively by another user. (Error 3028)

To ensure referential integrity in databases created by the Microsoft Jet database engine, your application must read the Microsoft Jet database's System.mdw file. Make sure the file is in the location specified in the SystemDB value of the \HKEY_LOCAL_MACHINE\ SOFTWARE\ Microsoft\ Office\8.0\ Access\ Jet\3.5\ Engines\Jet key in the Windows Registry.


Not a valid account name or password. (Error 3029)

You entered an invalid account (user) name or password.

User names

User names can be from 1 to 20 characters long and can include alphabetic characters, accented characters, numbers, spaces, and symbols, with the following exceptions:

  • The characters " / \ [ ] | < > + = ; , : ? *

  • Leading spaces

  • Control characters

User names are not case-sensitive.

Passwords

Passwords can be any combination of 14 or fewer characters, except control characters. Passwords are case-sensitive.


<Account name> isn't a valid account name. (Error 3030)

The specified account (user) name is not valid. User names can be from 1 to 20 characters long and can include alphabetic characters, accented characters, numbers, spaces, and symbols, with the following exceptions:

  • The characters " / \ [ ] | < > + = ; , : ? *

  • Leading spaces

  • Control characters

User names are not case-sensitive.


Not a valid password. (Error 3031)

You have typed an invalid password. Passwords can be any combination of 14 or fewer characters, except control characters. Passwords are case-sensitive.


Can't perform this operation. (Error 3032)

Possible causes:

  • You tried to delete the only user account in the group Admins. The group Admins must have at least one user account. If you want to delete this account, create a new account and add it to the group Admins, or add an existing account to the group Admins, and then delete the account.

  • You tried to put a user in a group to which the user already belongs, by appending either one of the following:
    • A CdbGroup object to a CdbUser object's Groups collection that already has a CdbGroup object of the same name.

    • A CdbUser object to a CdbGroup object's Users collection that already has a CdbUser object of the same name.


You don't have the necessary permissions to use the <name> object. Have your system administrator or the person who created this object establish the appropriate permissions for you. (Error 3033)

You do not have the necessary permission for the specified object. To change your permission assignments, see your system administrator or the object's creator.


You tried to commit or roll back a transaction without first using BeginTrans. (Error 3034)

You tried to commit or roll back a transaction that was not started with a BeginTrans statement.


Database has reached maximum size. (Error 3036)

To add data to this database, you must first reduce its size by deleting data.


Can't open any more tables or queries. (Error 3037)

You have reached the limit on the number of tables and queries that can be opened at one time. Close one or more tables or queries, and then try the operation again.


Couldn't create index; too many indexes already defined. (Error 3039)

You cannot create another index for this table. Consider deleting an existing index to make room for the new index.


Disk I/O error during read. (Error 3040)

The disk could not be read due to an internal disk or drive failure.

Possible causes:

  • You tried to read from a network drive, and the network is temporarily busy, or you are no longer connected to the network. Check the network connection, and then try the operation again.

  • The disk or drive has failed.


Can't open a database created with a previous version of your application. (Error 3041)

You tried to access a database that is in an outdated format. Compact the database and then try the operation again.


Out of MS-DOS file handles. (Error 3042)

Either close some files, close other applications, or increase the number of available MS-DOS file handles.

To increase the number of file handles

  1. Edit your Config.sys file using Microsoft Windows Notepad or another text editor. The Config.sys file is usually located in the root directory of your boot drive. If you do not have a Config.sys file on your system, you must create one that contains the line listed in step 2.

  2. Look for the line that reads FILES = x, where x is some number. Increase the number specified by the FILES command; the exact number of handles you enter depends on the applications you run and the number of files that are open at any given time. If other applications open multiple files, you may need to specify more file handles.

  3. As you increase the number of file handles, remember that each handle consumes more memory. For additional information, refer to your operating system manual.

  4. Exit Microsoft Windows.

  5. Reboot your system, and then try the operation again.


Disk or network error. (Error 3043)

An internal disk or drive failure prevents reading from or writing to the disk.

Possible causes:

  • You tried to use a network drive, and the network is temporarily busy, or you are no longer connected to the network. Check the network connection, and then try the operation again.

  • The disk or drive has failed.


<Path> isn't a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides. (Error 3044)

Possible causes:

  • You entered an invalid file specification that contains an invalid path. For example, you might have entered a path that does not exist or misspelled an element in the path specification.

  • The specified file is on a network drive and you aren't connected to that drive. Make sure the network is available, and then try the operation again.


Couldn't use <name>; file already in use. (Error 3045)

The specified file is currently being used by another user or session. Wait for the other user or session to finish working with the file, and then try the operation again.


Couldn't save; currently locked by another user. (Error 3046)

You tried to save information on a database page that is currently locked by another user. To save your changes, wait for the other user to finish, and then try the operation again.


Record is too large. (Error 3047)

You defined or imported a table with records larger than 2K. This error occurs when you enter data into the record — not when you define the table structure. Redefine the table by making some fields shorter, removing unneeded fields, or moving some fields to other tables.


Can't open any more databases. (Error 3048)

You have reached the limit on the number of databases that can be opened at one time. Close one or more databases and try the operation again.


Can't open database <name>. It may not be a database that your application recognizes, or the file may be corrupt. (Error 3049)

Possible causes:

  • You tried to open a non-Microsoft Jet database, such as a Btrieve, dBASE, or Paradox database or table. Instead, link the database or table to an existing Microsoft Jet database.

  • You tried to import or link a Paradox database or table, and the associated .px file couldn't be found. Make sure the .px file is in the same directory as the Paradox database or table, and then try the operation again.

  • If the specified database is a Microsoft Jet database, it is corrupted. You should attempt to repair the database. If the database can't be repaired, restore the database from a backup copy, or create a new database.


The Microsoft Jet database engine cannot open the file <name>. It is already opened exclusively by another user, or you need permission to view its data. (Error 3051)

Possible causes:

  • You must have permission to read data in the specified file in order to view its data. To change your permission assignments, see your system administrator or the table or query's creator.

  • You tried to open the indicated file exclusively, but another user already has the file open.


File sharing lock count exceeded. (Error 3052)

You have exceeded the maximum number of locks allowed on a recordset. This limit is specified by the MaxLocksPerFile setting in your system registry. The default value is 9500, and can be changed either by editing the registry with Regedit.exe or with the SetOption method.

Some other factors that may cause an application to hit this threshold include the following:

  • Amount of available memory

  • Size of rows in the recordset

  • Network operating system restrictions


Too many client tasks. (Error 3053)

You have too many copies of applications running at the same time. Close one or more instances.


Too many Memo or OLE Object fields. (Error 3054)

You tried to perform a Btrieve operation that involves too many Memo or OLE Object fields. Reduce the number of Memo and OLE Object fields, and then try the operation again.


Not a valid file name. (Error 3055)

You tried to use a file name that does not follow the naming conventions for your operating system. Specify the file name again, and then retry the operation.


Couldn't repair this database. (Error 3056)

This database is corrupted or it is not a Microsoft Jet database. Restore the corrupted Microsoft Jet database from a backup copy or create a new database.


Operation not supported on linked tables. (Error 3057)

Import data from the table, and then try the operation again.


Index or primary key can't contain a Null value. (Error 3058)

Possible causes:

  • You tried to add a Null value to a primary key field.

  • You tried to add a new record but did not enter a value in the field that contains the primary key.

  • You executed a query that tried to put a Null value in a primary key field.


Operation canceled by user. (Error 3059)

You stopped the operation before its normal completion. Some data changes may not have been saved.


Wrong data type for parameter <parameter>. (Error 3060)

You tried to use an argument with a data type that conflicts with the data type defined for this parameter. For example, you might have tried to use a string expression that expects a numeric argument with a parameter. Use an argument that has the correct data type, and then try the operation again.


Too few parameters. Expected <number>. (Error 3061)

This parameter query requires the specified number of parameters, which you did not supply. Provide the expected number of parameters, and run the query again.

In some cases, this message is generated when unknown field names or expressions are interpreted as query parameters. Be sure to enclose field names containing spaces or punctuation with square brackets [ ].


Duplicate output alias <name>. (Error 3062)

You tried to execute an SQL statement that has more than one alias with the same name. The following statement, for example, would produce this error:

SELECT LastName AS Name, FirstName AS Name FROM Employees;

Rename one or more of the aliases, and then try the operation again.


Duplicate output destination <name>. (Error 3063)

You tried to execute a query that contains more than one destination field with the same name.

Possible cause:

  • You created an SQL statement that includes an INSERT INTO, SELECT...INTO, or UPDATE statement that lists the specified field name more than once.

Remove the duplicate fields or alias the destination field names, and try the operation again.


Can't open action query <name>. (Error 3064)

You tried to open an action query using the OpenQueryDef method, which is an obsolete method originally valid only with select queries. The preferred method for executing an action query is to use the Execute method of the CdbQueryDef object.


Can't execute a select query. (Error 3065)

You tried to use the Execute method with a select query. The Execute method is valid only with action queries. Select queries contain a SELECT statement and can return records; action queries do not.


Query must have at least one destination field. (Error 3066)

This error occurs if you do not specify any destination field names when you create a query. Select at least one destination field.


Query input must contain at least one table or query. (Error 3067)

In Microsoft Jet databases, this error occurs if you do not select a table name when you create a query. Select at least one table or query.

In ODBCDirect databases, this error occurs if you attempt to execute a query that does not contain an SQL statement. Include at least one query or stored procedure call in the QueryDef object’s SQL property.


Not a valid alias name. (Error 3068)

The alias you entered does not follow standard naming conventions. Enter a new name, and then try the operation again.


The action query <name> cannot be used as a row source. (Error 3069)

You cannot use the name of an action query here. Instead, use the name of a select query. To run an action query, use the Execute method instead of the name of an action query as input to the FROM clause.


The Microsoft Jet database engine does not recognize <name> as a valid field name or expression. (Error 3070)

The specified name is not a recognized field name or a valid expression. In a query, this error can occur if you enter a name that improperly refers to a database, table, or field.


This expression is typed incorrectly, or it is too complex to be evaluated. For example, a numeric expression may contain too many complicated elements. Try simplifying the expression by assigning parts of the expression to variables. (Error 3071)

Possible causes:

  • You typed an expression that has invalid syntax. For example, an operand or operator may be missing, you may have typed an invalid character or comma, or you may have typed text without enclosing it with quotation marks ( " ). Check the expression to make sure you typed it correctly.

  • You typed an expression that is too complex. For example, a numeric expression may contain too many complicated elements. Try simplifying the expression by assigning some parts to variables.


Operation must use an updatable query. (Error 3073)

You tried to run, open, or modify a query that is not updatable.

Possible causes:

  • You attempted to run a query that tried to update a field that cannot be updated. For example, you may have created the query in such a way that you tried to update a field on the one side of a one-to-many relationship.

  • You tried to use the obsolete OpenQueryDef method on a query that is in a database opened for read-only access.

    The database is read-only for one of the following reasons:

    • You used the OpenDatabase method and opened the database for read-only access.

    • The database file has been defined as read-only in your network operating system.

    • In a network environment, you do not have write privileges for the database file.

    Close the database, resolve the read-only condition, and then reopen it for read/write access.

  • You do not have permission to make changes to the query. To change your permission assignments, see your system administrator or the query's creator.


Can't repeat table name <name> in FROM clause. (Error 3074)

You cannot list the table name more than once. Remove the extra occurrences of the table name or use an alias. If you are trying to join a table to itself, use an alias to change the second reference to the table.


<Message> in query expression <expression>. (Error 3075)

The expression you typed is not valid for the reason indicated in the message. Make sure you have typed field names and punctuation correctly, and then try the operation again.


<Name> in criteria expression. (Error 3076)

The expression you entered is not valid for the reason indicated in the message. Make sure you entered field names and punctuation correctly, and then try the operation again.


<Message> in expression. (Error 3077)

The expression you entered is not valid for the reason indicated in the message. Make sure you entered field names and punctuation correctly, and then try the operation again.


The Microsoft Jet database engine cannot find the input table or query <name>. Make sure it exists and that its name is spelled correctly. (Error 3078)

Possible causes:

  • The specified table or query does not exist.

  • You misspelled the table or query name. Check for missing underscores ( _ ) or other punctuation, and make sure you did not enter leading spaces.


The specified field <field> could refer to more than one table listed in the FROM clause of your SQL statement. (Error 3079)

The specified field reference could refer to more than one table listed in the FROM clause of your SQL statement. In the following example, the OrderID field exists in both the Orders and Order Details tables:

SELECT OrderID
FROM Orders, [Order Details];

Because the statement doesn't specify which table OrderID belongs to, it produces this error. To complete this operation, fully qualify the field reference by adding a table name. For example:

SELECT Orders.OrderID
FROM Orders, [Order Details];


Joined table <name> not listed in FROM clause. (Error 3080)

Add the specified table name to the FROM clause of the query, and then try the operation again.


Can't join more than one table with the same name <name>. (Error 3081)

You tried to join two or more tables that have the same name. Select different tables, rename one of the tables, or use an alias, and then try the operation again. If you are trying to join a table to itself, use a table alias to change the second reference to the table.


JOIN operation <operation> refers to a field that isn't in one of the joined tables. (Error 3082)

You tried to execute an SQL statement that contains an invalid join. This error occurs when you try to create a join on a field that is not in one of the joined tables. The following example produces this error.

SELECT Authors.FirstName, Titles.ISBN
FROM Authors, Titles, AuthorTitles,
Authors INNER JOIN Titles ON Authors.ID = AuthorTitles.ISBN;

The error occurs because the join involves the Authors and Titles tables, but the joined fields are in the Authors and AuthorTitles tables.


Can't use internal report query. (Error 3083)

You tried to use an SQL statement that includes an explicit reference to a disallowed internal report query. Remove the invalid reference, and then try the operation again.


Can't insert data with action query. (Error 3084)

You tried to run an append query using an action query for the input. Replace the action query with a select query, and then try the operation again.


Undefined function <name> in expression. (Error 3085)

You entered an SQL expression that includes a Function procedure name that cannot be recognized. Make sure the function exists, that it can be used in SQL expressions, or check the expression to make sure you entered the name correctly.


Couldn't delete from specified tables. (Error 3086)

You tried to delete data from one or more tables, but the deletion could not be completed.

Possible causes:

  • You do not have permission to modify the table. To change your permission assignments, see your system administrator or the table's creator.

  • The database was opened for read-only access. The database is read-only for one of these reasons:
    • You used the OpenDatabase method and opened the database for read-only access.

    • The database file is defined as read-only in the database server operating system or by your network.

    • In a network environment, you do not have write privileges for the database file.

To delete the data, close the database, resolve the read-only condition, and then reopen the file for read/write access.


Too many expressions in GROUP BY clause. (Error 3087)

You created an SQL statement with more than 10 fields listed in the GROUP BY clause. Remove some of the fields listed in the GROUP BY clause.


Too many expressions in ORDER BY clause. (Error 3088)

You created an SQL statement that has an ORDER BY clause with more than ten expressions. Remove some of the fields listed in the ORDER BY clause.


Too many expressions in DISTINCT output. (Error 3089)

You created an SQL statement that has an ALL, DISTINCT, or DISTINCTROW predicate with more than ten expressions. Remove the DISTINCT reserved word, or remove some of the fields listed in the DISTINCT predicate.


Resultant table not allowed to have more than one AutoNumber field. (Error 3090)

You tried to execute a query that would result in a table with more than one field that has an AutoNumber data type. Change the query to include only one AutoNumber field.


Can't use HAVING clause in TRANSFORM statement. (Error 3092)

If you want to specify selection criteria, use a WHERE clause.


ORDER BY clause <clause> conflicts with DISTINCT. (Error 3093)

You created an SQL statement with an ALL, DISTINCT, or DISTINCTROW predicate and an ORDER BY clause that contains a field not listed in the SELECT statement. Remove the DISTINCT reserved word, or remove the specified field from the ORDER BY clause.


ORDER BY clause <clause> conflicts with GROUP BY clause. (Error 3094)

This error can occur when you create a select query and specify grouped fields after sorted fields that are not grouped. For example, you created an SQL statement with the specified field out of sequence in the ORDER BY clause. Move the specified field to the left of the ungrouped fields, or remove the specified field from the ORDER BY clause.


Can't have aggregate function in expression <expression>. (Error 3095)

You cannot use an aggregate function in this expression.


Can't have aggregate function in WHERE clause <clause>. (Error 3096)

You cannot use an aggregate function in the WHERE clause of an SQL statement.


Can't have aggregate function in ORDER BY clause <clause>. (Error 3097)

You cannot use an aggregate function in the ORDER BY clause of an SQL statement.


Can't have aggregate function in GROUP BY clause <clause>. (Error 3098)

You cannot use an aggregate function in the GROUP BY clause of an SQL statement.


Can't have aggregate function in JOIN operation <operation>. (Error 3099)

You cannot use an aggregate function in the JOIN operation of an SQL statement.


Can't set field <name> in join key to Null. (Error 3100)

You have a join, and you tried to set a field on either side of the join to a Null value. Either select different fields or enter data in the fields, and then try the operation again.


The Microsoft Jet database engine can't find a record in the table <name> with key matching field(s) <name>. (Error 3101)

In a one-to-many relationship, you entered data on the "many" side for which there is no matching record on the "one" side. For example, this error occurs if you join a Customers table and Orders table on a CustomerID field, and then add an order using a CustomerID that does not exist in the Customers table.


Circular reference caused by <query reference>. (Error 3102)

You tried to execute a query that depends on itself for data. For example, this error occurs if you execute either of the following queries:

Query1

SELECT * FROM Employees, Query2;

Query2

SELECT * FROM Query1;

Redesign the queries to eliminate the dependency.


Circular reference caused by alias <name> in query definition's SELECT list. (Error 3103)

The specified alias created a reference that cannot be resolved. This error can occur, for example, if you enter the following SQL statement, in which A is the circular reference:

SELECT A + B AS C, C + D AS E, E + F AS A
FROM MyTable;

SELECT week1 + week2 as hours, hours + overtime as gross, gross + ytdpay as week1
FROM EmployeePay


Can't specify fixed column heading <value> in a crosstab query more than once. (Error 3104)

When you create a crosstab query with fixed column headings, the values you specify must be unique. Change one or more of the duplicate column headings, and then try the operation again.


Missing destination field name in SELECT INTO statement <statement>. (Error 3105)

Enter a destination field name in the specified statement, and then try the operation again.


Missing destination field name in UPDATE statement <statement>. (Error 3106)

Enter a destination field name in the specified statement, and then try the operation again.


Record(s) can't be added; no insert permission on <name>. (Error 3107)

You must have insert data permission for the specified table or query to insert data into it. To change your permission assignments, see your system administrator or the table or query's creator.


Record(s) can't be edited; no update permission on <name>. (Error 3108)

You must have update data permission for the specified table or query to replace data in it. To change your permission assignments, see your workgroup administrator or the table or query's creator.


Record(s) can't be deleted; no delete permission on <name>. (Error 3109)

You must have delete permission for the specified table or query in order to delete data. To change your permission assignments, see your system administrator or the table or query's creator.


Couldn't read definitions; no read definitions permission for table or query <name>. (Error 3110)

You must have read definitions permission for the specified table or query to read its definition. To change your permission assignments, see your system administrator or the table or query's creator.


Couldn't create; no modify design permission for table or query <name>. (Error 3111)

You tried to create the specified table or query, but you do not have the required modify design permission. To change your permission assignments, see your system administrator or the table or query's creator.


Record(s) can't be read; no read permission on <name>. (Error 3112)

You must have read permission for the specified table or query to view its data. To change your permission assignments, see your system administrator or the table or query's creator.


Can't update <field name>; field not updatable. (Error 3113)

Possible causes:

  • The specified field is part of a CdbTableDef or dynaset-type CdbRecordset object that cannot be updated. For example, this error occurs if you try to update an AutoNumber field.

  • You executed a query that combines updatable and nonupdatable CdbTableDef objects, and you tried to update one of the fields in the query's results (the resulting dynaset-type CdbRecordset).


Can't include Memo or OLE Object when you select unique values <statement>. (Error 3114)

Remove the DISTINCT reserved word or the Memo or OLE Object field from the statement.


Can't have Memo or OLE Object fields in aggregate argument <statement>. (Error 3115)

You cannot include Memo or OLE Object fields in an aggregate function.


Can't have Memo or OLE Object fields in criteria <criteria> for aggregate function. (Error 3116)

The HAVING clause of an SQL statement cannot include Memo or OLE Object fields.


Can't sort on Memo or OLE Object <clause>. (Error 3117)

The ORDER BY clause of an SQL statement cannot include Memo or OLE Object fields.


Can't join on Memo or OLE Object <name>. (Error 3118)

You cannot join Memo or OLE Object fields. The field you use to logically tie two or more tables together must be some other data type, such as text or integer.


Can't group on Memo or OLE Object <clause>. (Error 3119)

The GROUP BY clause of an SQL statement cannot include Memo or OLE Object fields.


Can't group on fields selected with '*' <table name>. (Error 3120)

You tried to execute a SELECT statement that groups or totals all fields in a single table, selected with an asterisk ( * ). This error occurs, for example, if you enter the following SQL statement:

SELECT Orders.* FROM Orders GROUP BY ShipVia;


Can't group on fields selected with '*'. (Error 3121)

You tried to execute a SELECT statement that groups or totals all fields from all tables, selected with an asterisk ( * ).

Possible cause:

  • You created an SQL statement that includes an aggregate function or GROUP BY clause that refers to a field you selected with an asterisk. This error occurs, for example, if you enter the following SQL statement:
    SELECT * FROM Orders GROUP BY ShipVia;


You tried to execute a query that doesn't include the specified expression <name> as part of an aggregate function. (Error 3122)

You tried to execute a query that does not include the specified expression as part of an aggregate function or grouping.

Possible cause:

  • You did not enter an aggregate function in the TRANSFORM statement.


Can't use '*' in crosstab query. (Error 3123)

You tried to execute a query that groups or totals fields selected with an asterisk ( * ). Choose specific fields, and then try the operation again.


Can't input from internal report query <name>. (Error 3124)

You tried to use an SQL statement that includes an explicit reference to a disallowed internal report query.


The database engine can't find <name>. Make sure it is a valid parameter or alias name, that it doesn't include invalid characters or punctuation, and that the name isn't too long. (Error 3125)

The specified name does not follow standard naming conventions or is not a valid parameter or alias name. Check your entry to make sure you have not included invalid characters or punctuation and that the name is not too long.


Invalid bracketing of name <name>. (Error 3126)

The specified name either cannot have brackets around it or the brackets are mismatched. Check your entry to make sure the brackets are properly matched, and then try the operation again.


The INSERT INTO statement contains the following unknown field name: <field name>. Make sure you've typed the name correctly, and try the operation again.(Error 3127)

You tried to use an INSERT INTO statement with the specified field name, but that field does not exist in the output table. Make sure you have typed the name correctly, and then try the operation again.


Specify the table containing the records you want to delete. (Error 3128)

You tried to execute a delete query but the query does not specify the name of the table containing the records you want to delete.

Possible cause:

  • You did not type an asterisk for each table in the ALL, DISTINCT, DISTINCTROW predicates. Instead, you typed field names (for example, Customers.Address instead of Customers.*).


Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'. (Error 3129)

Your SQL statement could not be recognized because it does not begin with one of the specified reserved words.


Syntax error in DELETE statement. (Error 3130)

You entered an SQL statement that has an invalid DELETE statement.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in FROM clause. (Error 3131)

You entered an SQL statement that has an invalid FROM clause.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in GROUP BY clause. (Error 3132)

You entered an SQL statement that has an invalid GROUP BY clause.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in HAVING clause. (Error 3133)

You entered an SQL statement that has an invalid HAVING clause.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in INSERT INTO statement. (Error 3134)

You entered an SQL statement that has an invalid INSERT INTO statement.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in JOIN operation. (Error 3135)

You entered an SQL statement that has an invalid join operation. It could be an inner join, outer join, or self-join.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


The LEVEL clause includes a reserved word or argument that is misspelled or missing, or the punctuation is incorrect. (Error 3136)

You entered an SQL statement that has an invalid reserved word clause.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in ORDER BY clause. (Error 3138)

You entered an SQL statement that has an invalid ORDER BY clause.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in PARAMETER clause. (Error 3139)

You entered an SQL statement with an invalid PARAMETERS declaration.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in PROCEDURE clause. (Error 3140)

You entered an SQL statement that has an invalid PROCEDURE clause.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect. (Error 3141)

You entered an SQL statement that has an invalid SELECT statement.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in TRANSFORM statement. (Error 3143)

You entered an SQL statement that has an invalid TRANSFORM statement.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in UPDATE statement. (Error 3144)

You entered an SQL statement that has an invalid UPDATE statement.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in WHERE clause. (Error 3145)

You entered an SQL statement that has an invalid WHERE clause.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


ODBC - call failed. (Error 3146)

ODBC – call failed. (Error 3146)

Using an ODBC connection, you tried to perform an operation on data in an ODBC data source. This error may occur when the ODBC data source is on a network drive and you are not connected to the network. Make sure the network is available, and then try the operation again.


ODBC -- connection to <name> failed. (Error 3151)

ODBC — connection to <name> failed. (Error 3151)

The ODBC connection to the specified ODBC database or table could not be made. If the ODBC database is accessed via a network connection, make sure the network is available, and then try the operation again.


ODBC -- couldn't find DLL <name>. (Error 3154)

ODBC — couldn't find DLL <name>. (Error 3154)

Using an ODBCconnection, you tried to perform an operation that requires the specified DLL.

Possible causes:

  • The DLL file is on a network drive and the network is not connected. Make sure the network is available, and then try the operation again.

  • The DLL file was not installed properly. Reinstall the ODBC driver, and then try the operation again.


ODBC -- insert on a linked table <table> failed. (Error 3155)

ODBC — insert on a linked table <table> failed. (Error 3155)

Using an ODBCconnection, you tried to insert data into an ODBC database; that insertion could not be completed.

Possible causes:

  • The insertion would have caused a rule violation.

  • The ODBC database is read-only, or you do not have permission to insert data in that database. Resolve the read-only condition, or see your system administrator or the person who created the database to obtain the necessary permissions.

  • The ODBC database is on a network drive and you aren't connected to the network. Make sure the network is available, and then try the operation again.


ODBC -- delete on a linked table <table> failed. (Error 3156)

ODBC — delete on a linked table <table> failed. (Error 3156)

Using an ODBCconnection, you tried to delete data from an ODBC database; the deletion could not be completed.

Possible causes:

  • The deletion would have caused a rule violation.

  • The ODBC database is read-only, or you do not have permission to delete data in that database. Resolve the read-only condition, or see your system administrator or the person who created the database to obtain the necessary permissions.

  • The ODBC database is on a network drive and the network is not connected. Make sure the network is available, and then try the operation again.


ODBC -- update on a linked table <table> failed. (Error 3157)

ODBC — update on a linked table <table> failed. (Error 3157)

Using an ODBCconnection, you tried to update data in an ODBC database; that update could not be completed.

Possible causes:

  • The update would have caused a rule violation.

  • The ODBC database is read-only, or you do not have permission to update data in that database. Resolve the read-only condition, or see your system administrator or the person who created the database to obtain the necessary permissions.

  • The ODBC database is on a network drive and the network is not connected. Make sure the network is available, and then try the operation again.


Couldn't save record; currently locked by another user. (Error 3158)

You tried to save a record that is on a database page currently locked by another user. To save your changes, wait for the other user to finish working with the record, and then try the operation again.


Not a valid bookmark. (Error 3159)

You tried to set a bookmark to an invalid string.

This error can occur if you set the Bookmark property to a string that is invalid or was not saved from previously reading a Bookmark property. For example, the following code produces this error:

Sub SetBookmark()
   Dim dbs As Database
   Dim rstEmployees As Recordset
   Dim strPlaceholder As String

   Set dbs = OpenDatabase("Northwind.mdb")
   Set rstEmployees = _
      dbs.OpenRecordset _
      ("Employees", dbOpenDynaset)
   strPlaceholder = "1"
   rstEmployees.Bookmark = strPlaceholder   ' Not a valid bookmark.
End Sub


Table isn't open. (Error 3160)

You tried to perform an operation on a table that has not been opened. Open the table, and then try the operation again.


Couldn't decrypt file. (Error 3161)

You tried to access an encrypted Btrieve or Paradox table, but the password you provided is not correct. Try the operation again and enter the correct password.


You tried to assign the Null value to a variable that isn't a Variant data type. (Error 3162)

You tried to assign a Null value to a variable that is not a Variant data type. Use the Dim statement to declare the variable as a Variant, and then try the operation again.


The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data. (Error 3163)

The field into which you tried to insert or paste data is not large enough to hold the data. Try inserting or pasting less data.


The field can't be updated because another user or process has locked the corresponding record or table. (Error 3164)

Possible cause:

  • You tried to update a field in a record or table that is currently locked by another user. Wait for the other user to finish working with the record or table, and then try the operation again.


Couldn't open .inf file. (Error 3165)

You tried to link a dBASE table, but the associated .inf file that contains index information about that table could not be opened or created.

Possible causes:

  • There is not enough disk space available to create the .inf file.

  • In a network environment, you do not have write privileges for the network drive.


Cannot locate the requested Xbase memo file. (Error 3166)

You tried to access a dBASE (.dbf) file, but the file's associated memo (.dbt) file could not be found. Make sure the .dbt file is in the same directory as the .dbf file, and then try the operation again.


Record is deleted. (Error 3167)

You referred to a record that you deleted or that another user in a multiuser environment deleted. Move to another record, and then try the operation again.


Invalid .inf file. (Error 3168)

You tried to access a dBASE table, but its associated .inf file is invalid or has become corrupted. Relink the table, making sure you specify the correct indexes.


The Microsoft Jet database engine could not execute the SQL statement because it contains a field that has an invalid data type. (Error 3169)

You tried to execute an SQL statement that contains a field that has an invalid field data type.

Possible causes:

  • You included a Memo or OLE Object field in an expression where it is not allowed.

  • You included a numeric aggregate function, such as Sum or StDev, that tried to perform a calculation on a Text field. Choose a different aggregate function.


Couldn't find installable ISAM. (Error 3170)

The DLL for an installable ISAM file could not be found. This file is required for linking external tables (other than ODBC or Microsoft Jet database tables). The locations for all ISAM drivers are maintained in the Windows Registry. These entries are created automatically when you install your application. If you change the location of these drivers, you need to correct your application Setup program to reflect this change and make the correct entries in the Registry.

Possible causes:

  • An entry in the Registry is not valid. For example, this error occurs if you're using a Paradox external database and the Paradox entry points to a nonexistent directory or driver. Exit the application, correct the Windows Registry, and try the operation again.

  • One of the entries in the Registry points to a network drive and that network is not connected. Make sure the network is available, and then try the operation again.


Couldn't find network path or user name. (Error 3171)

One or more entries in the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Paradox key of the Windows Registry is invalid. Correct the invalid entries, and then try the operation again.


Couldn't open Paradox.net. (Error 3172)

Possible causes:

  • The ParadoxNetPath value in the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Paradox Registry key is not valid. This error occurs if you're using the Paradox external database and the ParadoxNetPath value points to a nonexistent directory. Exit the application, correct the invalid entry, and try the operation again.

  • The ParadoxNetPath Registry value points to a network drive and you aren't connected to that network drive. Make sure the network drive is available, and then try the operation again.


Couldn't open table 'MSysAccounts' in the workgroup information file. (Error 3173)

This operation requires the System.mdw file, which contains the security and option settings for Microsoft Jet database tables.

Possible causes:

  • The SystemDB value of the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\8.0\Access\Jet\3.5\Engines\Jet key in the Windows Registry points to a network drive that is not connected. Make sure the network drive is available, and then try the operation again.

  • The System.mdw file is corrupted. If you have a backup copy of System.mdw, copy it to the location specified in the SystemDB entry in the Registry.


Couldn't open table 'MSysGroups' in the workgroup information file. (Error 3174)

This operation requires the System.mdw file, which contains the security and option settings for Microsoft Jet database tables.

Possible causes:

  • The SystemDB value of the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\8.0\Access\Jet\3.5\Engines\Jet key in the Windows Registry points to a network drive that is not connected. Make sure the network drive is available, and then try the operation again.

  • The System.mdw file is corrupted. If you have a backup copy of System.mdw, copy it to the location specified in the SystemDB entry in the Registry.


Date is out of range or is in an invalid format. (Error 3175)

Only dates from December 30, 1899, through December 30, 9999 are recognized.

Possible causes:

  • You entered a date that was outside the valid range.

  • You entered a valid date, but it wasn't in a recognized format. Make sure you entered it correctly, and then try the operation again.


Couldn't open file <name>. (Error 3176)

The specified text or spreadsheet file could not be opened. The specified file specification may be invalid, another user may be accessing the file, or you may not have read privileges for the file. Wait for the other user to finish using the file and then try the operation again, or contact your system administrator or network administrator.


Not a valid table name. (Error 3177)

The name you entered does not follow standard naming conventions. Enter a new name, and then try the operation again.


Encountered unexpected end of file. (Error 3179)

You tried to import a file that contains an end-of-file marker in an unexpected position.

Possible causes:

  • The import file is corrupted. Restore a backup copy of the import file, and then try the operation again.

  • The import/export specifications you are using do not match the data in the import file. Edit the import/export specifications, and then try the operation again.


Couldn't write to file <name>. (Error 3180)

You tried to export data to the specified text or spreadsheet file, but the file could not be modified.

Possible causes:

  • Another user is currently accessing the file. Wait for the other user to finish using the file, and then try the operation again.

  • The file has been defined as read-only in the operating system or by your network. Resolve the read-only condition, and then try the operation again.

  • In a network environment, you do not have write privileges for the file.

You may need to contact your system administrator or network administrator.


Invalid range. (Error 3181)

You attempted to import an invalid range of spreadsheet cells.


Invalid file format. (Error 3182)

Possible causes:

  • The file you tried to read or link is corrupted. Restore a backup copy of the file to your disk, and then try the operation again.

  • The file format is not recognized. If the file is a Btrieve, dBASE, or Paradox file, run Setup to install the installable ISAM, and then link the file.


Not enough space on temporary disk. (Error 3183)

You tried to perform an operation that requires more space than is available on the temporary disk. Your temporary disk location is based on the TEMP DOS environment variable, which was set when your system started.

For example, you may be trying to create a query that creates temporary files larger than the temporary disk. Reduce the size of the temporary files by accessing smaller amounts of data at one time or increase the size of the temporary disk.

You can increase the amount of available temporary disk space in several ways:

  • Select fewer records. Dynaset-type, forward-only – type, and snapshot-type CdbRecordset objects record keys and data to the temporary disk.

  • Select a different drive for your temporary disk.

  • If the temporary disk is a RAM disk, increase the amount of available RAM and the space allocated to the RAM disk, or move it to a fixed disk.

  • Free some space by deleting data or by removing unneeded tables, queries, forms, macros, and modules from your database.

  • Free some space by compressing deleted records out of your database.

  • If you still need additional space, consider removing other unused files from your disk.


Couldn't execute query; couldn't find linked table. (Error 3184)

Possible causes:

  • The linked table no longer exists or has been renamed or moved. Link the table and then try to execute the query again.

  • The linked table is on a network drive and you are not connected to the network. Make sure the network is available, and then try to execute the query again.


SELECT INTO on a remote database tried to produce too many fields. (Error 3185)

The Microsoft Jet database supports up to 255 fields per table, but the other database supports fewer fields. A SELECT INTO statement created a table with more fields than the remote database can support. Reduce the number of columns produced by the SELECT INTO statement, and then try the operation again.


Couldn't save; currently locked by user <name> on machine <name>. (Error 3186)

Possible cause:

  • You tried to save a record on a 2K database page that is currently locked by another user. Wait for the other user to finish working with the record, and then try the operation again.


Couldn't read; currently locked by user <name> on machine <name>. (Error 3187)

You tried to read information on a database page that is currently locked by the specified user. Wait for the other user to finish, and then try the operation again.


Couldn't update; currently locked by another session on this machine. (Error 3188)

You tried to update information that is currently locked by another session. Wait for the other session to finish or close the other session, and then try the operation again.


Table <name> is exclusively locked by user <name> on machine <name>. (Error 3189)

You can't access the specified table because it is exclusively locked by another user. Contact the other user, or wait for the other user to release the lock, and then try the operation again.


Too many fields defined. (Error 3190)

You tried to perform an operation that involves more than 255 fields. Reduce the number of fields, and then try the operation again.


Can't define field more than once. (Error 3191)

You tried to create a table in which more than one field was defined with the same name. Each field name in a table must be unique.


Couldn't find output table <name>. (Error 3192)

You tried to use an INSERT INTO statement with the specified table, which doesn't exist. Make sure you entered the name correctly, and then try the operation again.

If you are attempting to execute a make table query that creates the table for you, use the SELECT INTO syntax instead.


The database <database name> is already in use by another person or process. When the database is available, try the operation again. (Error 3196)

The specified database is currently being used exclusively by another user or session. Wait for the other user or session to finish working with the database, and then try the operation again.


The Microsoft Jet database engine stopped the process because you and another user are attempting to change the same data at the same time. (Error 3197)

This error can occur in a multiuser environment.

Another user has changed the data you are trying to update. This error can occur when multiple users open a table or create a CdbRecordset and use optimistic locking. Between the time you used the Edit method and the Update method, another user changed the same data.

To overwrite the other user's changes with your own, execute the Update method again.


Couldn't start session. Too many sessions already active. (Error 3198)

You tried to perform an operation that would have started a new session, but too many sessions are already active. Wait for one or more sessions to finish, and then try the operation again.


Couldn't find reference. (Error 3199)

You entered a file, table, or field reference that could not be found. Check the spelling and punctuation to make sure you entered the reference correctly, and then try the operation again.


The record cannot be deleted or changed because table <name> includes related records. (Error 3200)

You tried to perform an operation that would have violated referential integrity rules for related tables. For example, this error occurs if you try to delete or change a record in the "one" table in a one-to-many relationship when there are related records in the "many" table.

If you want to delete or change the record, first delete the related records from the "many" table.


You can't add or change a record because a related record is required in table <name>. (Error 3201)

You tried to perform an operation that would have violated referential integrity rules for related tables. For example, this error occurs if you try to change or insert a record in the "many" table in a one-to-many relationship, and that record doesn't have a related record in the table on the "one" side.

If you want to add or change the record, first add a record to the "one" table that contains the same value for the matching field.


Couldn't save; currently locked by another user. (Error 3202)

Possible cause:

  • You tried to save a record on a 2K database page that is currently locked by another user. Wait for the other user to finish working with the record, and then try the operation again.


Subqueries cannot be used in the expression <expression>. (Error 3203)

The specified expression contains a subquery or other expression that functions as a subquery.

Possible cause:

  • You used a SELECT statement that includes an aggregate function that evaluates another aggregate function. This error occurs, for example, if you execute the following statement:
    TRANSFORM Sum([OrderAmount]) AS Sum1
SELECT Sum([Sum1]) AS Sum2, OrderID, Sum([Sum2]) AS Expr1
FROM Orders
GROUP BY OrderID
PIVOT ShipName;

    The <expression> parameter of the alert would contain the expression Sum([Sum2]) from the SELECT clause, because this references an alias used in the same SELECT statement and acts as a subquery against Sum([Sum1]).


Database already exists. (Error 3204)

You tried to create or rename a database using a name that already exists. Enter a different name, and then try the operation again.


Too many crosstab column headers <value>. (Error 3205)

You executed an SQL statement that tried to create too many columns. The specified value is the column that produced this error.

You can reduce the number of columns by adding additional conditions to the WHERE clause or, if there is no WHERE clause, add one.


Can't create a relationship between a field and itself. (Error 3206)

You tried to create a relationship between a field and itself. Choose a different field for the primary or related table, and then try the operation again.


Operation not supported on a Paradox table with no primary key. (Error 3207)

Run the application that created the table and add a primary key. Then, try the operation again.


Invalid Deleted setting in the Xbase key of the Windows Registry. (Error 3208)

There is an invalid Deleted setting in the Xbase key of the Windows Registry.

To fix the Deleted setting

  1. Exit your application.

  2. Start the Registry Editor, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Xbase key, and select the Deleted value.

  3. On the Edit menu, click Modify.

  4. Correct the Deleted data in the Value data box.

  5. Restart your application, and then try the operation again.


The connection string is too long. (Error 3210)

The connection string in the IN clause of an SQL statement cannot be longer than 255 characters. Correct your entry, and then try the operation again.


The database engine couldn't lock table <name> because it's already in use by another person or process. (Error 3211)

To complete this operation, a table currently in use by another user must be locked. Wait for the other user to finish working with the table, and then try the operation again.


Couldn't lock table <name>; currently in use by user <name> on machine <name>. (Error 3212)

The table cannot be locked because it is currently in use. Wait for the other user's transaction to complete, and then try the operation again.


Invalid Date setting in the Xbase key of the Windows Registry. (Error 3213)

There is an invalid Date setting in the Xbase key of the Windows Registry.

To fix the Date setting

  6. Exit your application.

  7. Start the Registry Editor, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Xbase key, and select the Date value.

  8. On the Edit menu, click Modify.

  9. Correct the Date data in the Value data box.

  10. Restart your application, and then try the operation again.


Invalid Mark setting in the Xbase key of the Windows Registry. (Error 3214)

There is an invalid Mark setting in the Xbase key of the Windows Registry.

To fix the Mark setting

  11. Exit your application.

  12. Start the Registry Editor, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Xbase key, and select the Mark value.

  13. On the Edit menu, click Modify.

  14. Correct the Mark data in the Value data box.

  15. Restart your application, and then try the operation again.


Too many Btrieve tasks. (Error 3215)

Too many applications are using the Btrieve driver. In a multiuser environment, this error can occur when too many users access the same server. Contact your system administrator or network administrator.


Parameter <name> specified where a table name is required. (Error 3216)

You created a parameter query that specifies an invalid parameter type. The following example produces this error:

PARAMETERS Param1 Text;
INSERT INTO Param1
SELECT *
FROM Customers;

Param1 is a text parameter, but the INSERT INTO statement expects a table name.

Change the parameter type from Text to TableID, and then try the operation again.


Parameter <name> specified where a database name is required. (Error 3217)

You created a parameter query that specifies an invalid parameter type. The following example produces this error:

PARAMETERS Param1 Text;
SELECT CustomerID
FROM Customers IN Param1;

Param1 is a text parameter, but the FROM clause requires a database parameter.

Change the parameter type from Text to Database, and then try the operation again.


Couldn't update; currently locked. (Error 3218)

You tried to update data that is located on a page that is currently locked.

Possible causes:

  • You tried to save a query that is being used by someone else. To save your query, wait for the other user to finish or enter a different name, and then try the operation again.

  • You tried to use the Edit method on a data page containing a record that is already open or locked.


Invalid operation. (Error 3219)

Possible causes:

  • You tried to write to a read-only property. See the Help topic for the property to determine whether it is read/write.

  • You tried to use a method or property on a type of CdbRecordset object that the method or property doesn't apply to.

  • You tried to append a property to a Properties collection of an object that does not support user-defined properties.

  • You tried to use the Update method on a read-only CdbRecordset object.


Incorrect collating sequence. (Error 3220)

You tried to link a Paradox table that was created with an international sort order that is not the same as the one you are using.


Invalid settings in the Btrieve key of the Windows Registry. (Error 3221)

A setting in the Btrieve key of the Windows Registry is not valid. For example, this error occurs if the /l: or /f: settings in the options entry are invalid.

To fix the Windows Registry settings

  16. Exit your application.

  17. Start the Registry Editor, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Btrieve key, and select the value that needs to be fixed.

  18. On the Edit menu, click Modify.

  19. Correct the data in the Value data box.

  20. Restart your application, and then try the operation again.


Query can't contain a Database parameter. (Error 3222)

Change the parameter field data type for this parameter query to a valid field data type, and then try the operation again.


<Parameter name> is invalid because it is too long or contains invalid characters. (Error 3223)

The parameter name is too long or contains invalid characters. Correct the name, and then try the operation again.


Can't read Btrieve data dictionary. (Error 3224)

Restore a backup copy of the DDF file, and then try the operation again.


Encountered a record locking deadlock while performing a Btrieve operation. (Error 3225)

You tried to lock a record during an update, insert, or delete operation on a linked Btrieve table, and another user is also trying to lock the same record. Cancel the operation, wait for the other user to finish, and then try the operation again.


Errors encountered while using the Btrieve DLL. (Error 3226)

An unexpected error occurred when you tried to access data in a linked Btrieve table. Try the operation again, or contact your system administrator or network administrator.


Invalid Century setting in the Xbase key of the Windows Registry. (Error 3227)

There is an invalid Century setting in the Xbase key of the Windows Registry.

To fix the Century setting

  21. Exit your application.

  22. Start the Registry Editor, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Xbase key, and select the Century value.

  23. On the Edit menu, click Modify.

  24. Correct the Century data in the Value data box.

  25. Restart your application, and then try the operation again.


Selected collating sequence not supported by the operating system. (Error 3228)

There is an invalid CollatingSequence setting in the Paradox key of the Windows Registry.

To fix the CollatingSequence setting

  26. Exit your application.

  27. Start the Registry Editor, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Paradox key, and select the CollatingSequence value.

  28. On the Edit menu, click Modify.

  29. Specify either ASCII or International in the Value data box.

  30. Restart your application, and then try the operation again.


Btrieve -- can't change field. (Error 3229)

Btrieve — can't change field. (Error 3229)

You tried to update a field in a Btrieve table that is part of an index that can't be modified. Use Novell Xtrieve or another program to change the attribute of the index that can't be modified, and then try the operation again.


Out-of-date Paradox lock file. (Error 3230)

You tried to use a Paradox table, but the table's associated lock (.lck) file is outdated. Delete the .lck file, and then try the operation again.


ODBC -- field would be too long; data truncated. (Error 3231)

ODBC — field would be too long; data truncated. (Error 3231)

You tried to perform a task on an ODBC data source that would have resulted in a field that is too long. The data has been truncated to the maximum allowable length.


ODBC -- couldn't create table. (Error 3232)

ODBC — couldn't create table. (Error 3232)

You tried to export a table to an ODBC database and the table could not be created. This error can occur if the ODBC database is read-only, or you do not have permission to create a table in that database. Resolve the read-only condition, or see your system administrator or the person who created the database to obtain the necessary permission.


ODBC -- remote query timeout expired. (Error 3234)

ODBC — remote query timeout expired. (Error 3234)

The ODBC server may not be properly installed or a required network connection is not active. Try increasing the value of the QueryTimeout property.


ODBC -- data type not supported on server. (Error 3235)

ODBC — data type not supported on server. (Error 3235)

The ODBC server does not support the same SQL data types as the database engine or your application. The data has not been placed on the server.


ODBC -- data out of range. (Error 3238)

ODBC — data out of range. (Error 3238)

Using an ODBC connection, you tried to read from or write to an ODBC database, and the data is not within the prescribed limits.


Too many active users. (Error 3239)

In a multiuser environment, Microsoft Jet databases support up to 255 concurrent users. Wait for one or more users to stop using the system, and then try the operation again.


Btrieve -- missing Btrieve engine. (Error 3240)

Btrieve — missing Btrieve engine. (Error 3240)

You tried to perform an operation that requires the specified file. To use DAO to read and write data to a Btrieve file, you must have a copy of the stand-alone Btrieve for Windows engine. This file must be in your \Windows\System directory.

If you do not have a copy of this file, you can purchase Btrieve for Windows by contacting your local software dealer.


Btrieve -- out of resources. (Error 3241)

Btrieve — out of resources. (Error 3241)

While working with a Btrieve file, your application ran out of resources.

To increase the number of resources

  31. Exit your application.

  32. Start the Registry Editor, and navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Btrieve key.

  33. Increase one or more settings in the Btrieve key of the Windows Registry.

  34. Restart your application, and then try the operation again.

For more information, refer to your Btrieve documentation.


Invalid reference in SELECT statement. (Error 3242)

You entered an invalid field or table reference in the SELECT statement. For example, the reference may be misspelled or does not exist.


None of the import field names match fields in the appended table. (Error 3243)

At least one field name in the import table and the appended table must match.


Can't import password-protected spreadsheet. (Error 3244)

Return to the application that was used to save the spreadsheet, save the spreadsheet again without a password, and then try to import the spreadsheet again.


Couldn't parse field names from the first row of the import table. (Error 3245)

The first row of data contains invalid field names, such as quoted and unquoted strings in the same field name. In the following example, the third and fourth field names can't be parsed:

"Name", Date, "ID " Number, Phone" Number"

The first two fields are valid, but the third and fourth are not because they contain nonspace characters outside the quotation marks.

Check the import table for properly matched quotation marks, and then try the import operation again.


Operation not supported in transactions. (Error 3246)

You tried to perform an operation that is not valid within a transaction. A transaction can be one you create using a BeginTrans statement, or an internal transaction created by the Microsoft Jet database engine, such as when you delete multiple records in a single operation.


ODBC -- linked table definition has changed. (Error 3247)

ODBC — linked table definition has changed. (Error 3247)

The definition or structure of a linked table changed since you created the link. Delete the link, and then relink the table.


Invalid NetworkAccess setting in the Windows Registry. (Error 3248)

There is an invalid NetworkAccess setting in the Windows Registry.

To complete this operation

  35. Exit your application.

  36. Start the Registry Editor, and navigate to the NetworkAccess value.

    Depending on which installable ISAM you are trying to use, the invalid entry is in the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Btrieve or \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Xbase key.

  37. On the Edit menu, click Modify.

  38. Specify either On or Off in the Value data box.

  39. Restart your application, and then try the operation again.


Invalid PageTimeout setting in the Windows Registry. (Error 3249)

There is an invalid PageTimeout setting in the Windows Registry.

To complete this operation

  40. Exit your application.

  41. Start the Registry Editor, and navigate to the PageTimeout value.

    Depending on which installable ISAM you are trying to use, the invalid entry is in the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Btrieve or \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Xbase key.

  42. On the Edit menu, click Modify.

  43. Specify a new value in the Value data box.

  44. Restart your application, and then try the operation again.


Couldn't build key. (Error 3250)

When building a primary index, the Microsoft Jet database engine could not build a primary key. Make sure the key fields are named properly and that there are no duplicate records based on this key.

This error can occur when you use the Seek method and pass it a value for a field that is not part of the index. For example, suppose you want to use the Seek method on a CdbRecordset whose current index uses the LastName field of the underlying table, and you write it this way:

rstEmployees.Seek "=", "Smith", "Joe"

Microsoft Jet will try to construct a primary key from two fields, but because one field is indexed, the attempt will fail and this error results.


Operation is not supported for this type of object. (Error 3251)

You were attempting to execute a method or assign a value to a property that is usually valid for the object, but is not supported in this specific instance. For example, the Edit method is generally valid for CdbRecordset objects, but not for a snapshot-type CdbRecordset. This error could also occur in cases where the operation is not permitted due to the type or status of the object—as when trying to use the MovePrevious method on a forward-only–type CdbRecordset. Some operations are also not supported, depending on if you are accessing a Microsoft Jet or an ODBC data source.


Can't open a form whose underlying query contains a user-defined function that attempts to set or get the form's RecordsetClone property. (Error 3252)

This error can occur in Microsoft Access if you execute a query that includes a user-defined function in its output and then create a form based on that query.


ODBC -- Can't lock all records. (Error 3254)

ODBC — Can't lock all records. (Error 3254)

Using an ODBC , you tried to lock all of the records in an ODBC database.


Index file not found. (Error 3256)

You tried to access a dBASE table, but one of the indexes listed in the table's associated .inf file could not be found. The index may have been renamed, moved, or deleted. Either relink the table, or use Microsoft Windows Notepad or another text editor to update the .inf file.


Syntax error in WITH OWNERACCESS OPTION declaration. (Error 3257)

Possible causes:

  • The WITH OWNERACCESS OPTION declaration is incomplete or includes a space between OWNER and ACCESS.

  • The declaration appears in an unexpected and disallowed position in the SQL statement. For example:
    SELECT * WITH OWNERACCESS OPTION FROM [My Table];

    The WITH OWNERACCESS OPTION declaration should appear at the end of the SQL statement, usually after the ORDER BY clause, if present:

    SELECT * FROM [My Table] WITH OWNERACCESS OPTION;


The SQL statement couldn't be executed because it contains ambiguous outer joins. To force one of the joins to be performed first, create a separate query that performs the first join and then include that query in your SQL statement. (Error 3258)

You tried to execute an SQL statement that contains multiple joins; the results of the query can differ depending on the order in which the joins are performed. For example, this error can occur if you execute the following SQL statement:

SELECT * FROM Customers, Orders, [Order Details],
Customers LEFT JOIN Orders
ON Customers.CustomerID = Orders.CustomerID,
Orders INNER JOIN [Order Details]
ON Orders.OrderID = [Order Details].OrderID;

Executing this statement produces an error because the order of the joins is ambiguous. To force one of the joins to be performed first, create a separate query that performs the first join and then include that query in your SQL statement. The following queries illustrate how you might construct the preceding query so that the INNER JOIN operation is performed before the LEFT JOIN and RIGHT JOIN operation:

Query1

SELECT * FROM Orders, [Order Details],
Orders INNER JOIN [Order Details]
ON Orders. OrderID = [Order Details].OrderID;

Query2

SELECT * FROM Customers, Query1,
Customers LEFT JOIN Query1
ON Customers.CustomerID = Orders.CustomerID;


Invalid field data type. (Error 3259)

The data type specified in the Field object's Type property is not valid. Choose one of the valid types as shown in the Type property Help topic.


Couldn't update; currently locked by user <name> on machine <name>. (Error 3260)

You tried to update data that is located on a page that is currently locked.

Possible causes:

  • You tried to save a query being used by someone else. To save your query, wait for the other user to finish or enter a different name, and then try the operation again.

  • You tried to use the Edit method on a data page containing a record that is already open or locked.


Table <name> is exclusively locked by user <name> on machine <name>. (Error 3261)

You tried to use a table that is currently open for exclusive access by the specified user. Wait for the other user to finish working with the table, and then try the operation again.


Couldn't lock table <name>; currently in use by user <name> on machine <name>. (Error 3262)

You tried to lock a table while opening it, but the table cannot be locked because it is currently in use. Wait a moment, and then try the operation again.


Invalid Database object. (Error 3263)

The CdbDatabase object specified is not the result of the OpenDatabase method, or it has been modified and is no longer valid.


No field defined -- cannot append TableDef or Index. (Error 3264)

No field defined — cannot append TableDef or Index. (Error 3264)

You cannot append a CdbTableDef until you define one or more fields. Use the CreateField method to create fields, append them to the Fields collection of your CdbTableDef object, and then append the CdbTableDef object to the TableDefs collection.


Item not found in this collection. (Error 3265)

An attempt to reference a name in a collection failed.

Possible causes:

  • The object does not exist in this collection. Make sure the object is appended to a collection before referencing it.

  • There is more than one object with this name in the collection; using its name is an ambiguous reference. Reference the object by its ordinal position in the collection (for example, Recordsets(3)).


Can't append a Field that is already a part of a Fields collection. (Error 3266).

A CdbField object was specified as an argument to an Append operation when it already is a member of an existing Fields collection. Use the CreateField method to declare a new CdbField object and specify its values, and retry the operation with the new CdbField object.


Property can be set only when the Field is part of a Recordset object's Fields collection. (Error 3267)

This property is valid only for CdbField objects that are part of a CdbRecordset object's Fields collection.


Can't set this property once the object is part of a collection. (Error 3268)

An attempt was made to change the value of a property of an object (CdbTableDef, CdbField, and so on) that is already appended to a collection.


Can't append an Index that is already a part of an Indexes collection. (Error 3269)

An CdbIndex object was specified as an argument to an Append operation when it already is a member of an existing Indexes collection. Use the CreateIndex method to declare a new CdbIndex object and specify its values, and retry the operation with the new CdbIndex object.


Property not found. (Error 3270)

The specified property could not be found.

Possible causes:

  • The property does not exist. Check the spelling of the property in your code.

  • If the property is user-defined, it may have been deleted from the collection.


Invalid property value. (Error 3271)

Possible causes:

  • The setting for the Value property of the CdbParameter object is too long or is otherwise incorrect.

  • The CdbIndex object name is a zero-length string (" "). You must enter a name for the Index object when appending the object to the Indexes collection.

  • The CdbWorkspace object name is a zero-length string. You must enter a name for the CdbWorkspace object when appending the object to a Workspaces collection.


Object isn't a collection. (Error 3272)

You've referred to an object as though it were a collection. For example, a statement such as qrySales.Refresh or qrySales(2) causes this error.


Method not applicable for this object. (Error 3273)

You tried to use a method on an object that does not support that method. Refer to the Summary topic for the object to see a list of valid methods for that object.


External table isn't in the expected format. (Error 3274)

The format of the table has changed since it was linked. Link the table again, and then retry the operation.


Unexpected error from external database driver <error number>. (Error 3275)

The specified external database driver returned an error. This error can be caused by performing an operation not supported on this type of external database.


Invalid database object reference. (Error 3276)

The CdbDatabase object specified is not the result of the OpenDatabase method, or it has been modified and is no longer valid.


Can't have more than 10 fields in an index. (Error 3277)

You defined an index with more than ten fields. Reduce the number of fields to ten or less.


The Microsoft Jet database engine has not been initialized. (Error 3278)

The database engine cannot be initialized.

Possible causes:

  • There is a conflict with another application that uses the Microsoft Jet database engine. Quit all other applications, and then restart your application.

  • An error occurred during installation and setup. Reinstall your application.


The Microsoft Jet database engine has already been initialized. (Error 3279)

You attempted to initialize the Microsoft Jet database engine, but it has already been initialized.


Can't delete a field that is part of an index or is needed by the system. (Error 3280)

To delete a field that is part of an index, you must first delete the index.


Can't delete this index or table. It is either the current index or is used in a relationship. (Error 3281)

If the index or table is used in a relationship, you must delete the relationship before you can delete the index or table. If the index is specified as the current index by the CdbIndex property, you must set the property to a different index before you can delete the index.


Operation not supported on a table that contains data. (Error 3282)

You cannot add a field or create an index on a linked table that contains data. Once a table is populated with data, you cannot change the table design or indexes. Create a new table with the altered design and transfer the data to it using an action query.


Primary key already exists. (Error 3283)

You're attempting to define a second primary key for this table. Each table can have only one primary key. Remove the reference to the second primary key.


Index already exists. (Error 3284)

You cannot have two indexes with the same name in a table. Rename one of the indexes.


Invalid index definition. (Error 3285)

Possible causes:

  • You are using the same field twice in an index or relationship, which the Microsoft Jet database engine does not permit.

  • You are creating a relationship using fields with data types that do not match. In Microsoft Jet databases, you can only relate fields with identical data types or an AutoNumber field with a Number field set to a Long Integer.


Format of memo file doesn't match specified external database format. (Error 3286)

Your application cannot read the memo file associated with the database you are trying to import or link and consequently cannot import or link the file. The memo file may be in the wrong format; for example, if you selected dBASE IV as the data source and the memo file is in a FoxPro format.


Can't create index on the given field. (Error 3287)

You are trying to create an index on a Memo or OLE Object field. Specify another field, and then try the operation again.

This can also occur if you try to create an index on a Btrieve table on a 1-byte field.


Paradox index is not primary. (Error 3288)

You are attempting to create an index on a Paradox table for which no other indexes are defined. The first index created on a Paradox table must be a primary index.

Possible solutions:

  • Redefine the index as the primary index.

  • If the index you're attempting to create is not the primary index, create the primary index first.


Syntax error in CONSTRAINT clause. (Error 3289)

You entered an SQL statement that includes an invalid CONSTRAINT clause.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in CREATE TABLE statement. (Error 3290)

You entered an SQL statement that includes an invalid CREATE TABLE statement.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in CREATE INDEX statement. (Error 3291)

You entered an SQL statement that includes an invalid CREATE INDEX statement.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in field definition. (Error 3292)

A syntax error occurred in the field definition of a CREATE TABLE or ALTER TABLE statement.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in ALTER TABLE statement. (Error 3293)

You entered an SQL statement that includes an invalid ALTER TABLE statement.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in DROP INDEX statement. (Error 3294)

You entered an SQL statement that has an invalid DROP INDEX statement.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Syntax error in DROP TABLE or DROP INDEX. (Error 3295)

You entered an SQL statement that has an invalid DROP statement.

Possible causes:

  • A reserved word or argument name is misspelled or missing.

  • Punctuation is incorrect.


Join expression not supported. (Error 3296)

Possible causes:

  • Your SQL statement contains multiple joins in which the results of the query can differ, depending on the order in which the joins are performed. You may want to create a separate query to perform the first join, and then include that query in your SQL statement.

  • The ON statement in your JOIN operation is incomplete or contains too many tables. You may want to put your ON expression in a WHERE clause.


Couldn't import table or query. No records found, or all records contain errors. (Error 3297)

The Microsoft Jet database engine could not find the table or query you tried to import, or no records were found at the specified source, or all records contained errors. Check the path you specified and try it again.


There are several tables with that name. Please specify owner in the format 'owner.table'. (Error 3298)

More than one table with that name exists in the remote ODBC data source. To resolve the ambiguity, specify the owner of the table you want to access, using the owner.table syntax.


ODBC Specification Conformance Error <message>. Report this error to the developer of your application. (Error 3299)

This error can be caused by any of a number of problems with your ODBC driver. Write down the error number indicated in the message and report it to the developer of the application, who can then report it to the driver vendor.


Can't create a relationship. (Error 3300)

You are attempting to create a relationship that is not allowed. For example, the tables may be in different databases.


Can't perform this operation; features in this version are not available in databases with older formats. (Error 3301)

The database was stored in an earlier version of the Microsoft Jet database engine that does not support this feature. Either the database needs to be converted to Microsoft Jet version 2.0 or 3.0 format or this particular operation needs to be revised to avoid using the unsupported feature.


Can't change a rule while the rules for this table are in use. (Error 3302)

A record in this table has been changed by another user, or has been changed by you in a separate session of your application, and is currently locked. You cannot modify the rules in a table while a record in that table is locked.

If you have locked the record in a separate session, save the record, and then make your changes. If another user has locked the record, wait until the user is finished, and then save your rule modifications.


Can't delete this field. It's part of one or more relationships. (Error 3303)

You are trying to delete a field for which relationships have been defined in the database. To delete the field, you must first delete its relationships.


You must enter a personal identifier (PID) consisting of at least 4 and no more than 20 characters and digits. (Error 3304)


Invalid connection string in pass-through query. (Error 3305)

The connection string for a pass-through query should begin with "ODBC;".


You've written a subquery that can return more than one field without using the EXISTS reserved word in the main query's FROM clause. Revise the SELECT statement of the subquery to request only one field. (Error 3306)


The number of columns in the two selected tables or queries of a union query don't match. (Error 3307)

The two tables or queries joined by the UNION operation must generate the same number of columns. Remove columns from the SELECT statement that has too many columns or include more columns in the SELECT statement that has too few.

Note You can include constants instead of columns in the SELECT statement that has too few columns. For example, the following union query generates three columns from the first SELECT statement but one column and two constants in the second SELECT statement. The query returns all countries in the Employees and Regions tables. From the Employees table, the query also returns the first and last name of an employee. If the country value is from the Regions table, however, the query returns Null in the First Name and Last Name columns.

SELECT Country, FirstName, LastName FROM Employees
UNION SELECT Country, NULL, NULL FROM Regions;


Invalid TOP argument in select query. (Error 3308)

An invalid parameter appeared in the TOP clause of a SELECT statement. The value placed after the TOP reserved word must be a positive integer. If the PERCENT reserved word is also used, the integer cannot be greater than 100.


Property setting can't be larger than 2K. (Error 3309)

You are trying to set a property value of an object to a size greater than the largest permissible size of 2K. Shorten the length of the property value.


This property isn't supported for external data sources or for databases created with a previous version of Microsoft Jet. (Error 3310)

You attempted to set or check a property that is not available for this object in a database stored in a Microsoft Jet database version 1.x, 2.x, or in an external data source. Search for the object in Help, and then display the Summary topic for the object to see a list of its valid properties.


Property specified already exists. (Error 3311)

You tried to append a new CdbProperty object to a collection that contains a property of the same name. Check to see whether you've misspelled the new CdbProperty object's Name property, or refer to the Help topic for the existing property of the same name to see whether you need to create a new CdbProperty object.


Validation rules and default values can't be placed on system or linked tables. (Error 3312)

You are trying to set the DefaultValue, ValidationRule, ValidationText, or Required property on a table, field, or other object that is prohibited by your application. For example, you are setting a property on a system object.


Can't place this validation expression on this field. (Error 3313)

You are trying to set validation properties on a field (such as an AutoNumber or OLE Object field) that does not allow this type of property. Use a different field to validate data or, if you have not added data to the table, redefine the data type for the field.


The field <name> can't contain a Null value because the Required property for this field is set to True. Enter a value in this field. (Error 3314)

The Required property for this field is set to True, prohibiting the entry of a Null in the field. Enter a value in the field.


Field <name> can't be a zero-length string. (Error 3315)

The AllowZeroLength property for this field is set to False, prohibiting the entry of a zero-length string in the field. Enter a different value in the field.


<Table-level validation text>. (Error 3316)

A table-level validation rule was violated.


One or more values are prohibited by the validation rule <rule> set for <name>. Enter a value that the expression for this field can accept. (Error 3317)

The ValidationRule property for this field contains an expression that limits the values that can be entered in the field. Enter a value that is not prohibited by the expression.


Values specified in a TOP clause are not allowed in delete queries or reports. (Error 3318)

Top values, that is, those specified in a TOP clause of a SELECT statement, are not allowed in delete queries or in reports.


Syntax error in union query. (Error 3319)

There is a syntax error in an SQL string of the union query.

Possible causes:

  • A reserved word or argument name is misspelled.

  • A reserved word or argument is missing.

  • Punctuation is incorrect.


<Error> in table-level validation expression. (Error 3320)

An error occurred in a table-level validation rule expression or its default value expression. This could be a syntax error or some other kind of error.


No database specified in connection string or IN clause. (Error 3321)

The Microsoft Jet database engine is unable to connect to an external ISAM database because you have not specified the name of the database to connect to. When connecting to an external source of data, specify a database name.

Possible causes:

  • The connection string in the FROM clause of the SELECT statement is missing the parameter, DATABASE=.

  • The IN clause of the SELECT statement includes a database type argument (indicating to select the data from an external database) but it's missing a database name argument.


Crosstab query contains one or more invalid fixed column headings. (Error 3322)

The list of entries for a fixed column heading of a crosstab query (the PIVOT clause in a TRANSFORM statement) is not valid.

Possible causes:

  • There are no entries in the list. There must be at least one value in the parentheses following the IN reserved word in the PIVOT clause.

  • A blank entry appears in the list. Two commas in a row (,,) create a blank entry.

  • The list contains a field name of more than 64 characters.

Correct the PIVOT clause and execute the query again.


The query cannot be used as a row source. (Error 3323)

Possible cause:

  • The query being used as a record source is an action query or a data-definition query.


The query is a DDL query and cannot be used as a row source. (Error 3324)

You tried to run an action query or data-definition query without using the Execute method.


Pass-through query with ReturnsRecords property set to True did not return any records. (Error 3325)

A pass-through query did not return any records even though the ReturnsRecords property is set to True. If a pass-through query does not return records, set the ReturnsRecords property to False.


This Recordset is not updatable. (Error 3326)

You attempted to edit data in a field that is bound to a snapshot-type CdbRecordset object. Snapshot fields in a Microsoft Jet database cannot be edited.


Can be present only in version 1.0 format. (Error 3334)

You are attempting to use a feature that is no longer supported in the current version of the application.


Btrieve: Invalid IndexDDF option in initialization setting. (Error 3336)

The setting for the IndexDDF value in the Btrieve key of the Windows Registry is not valid. The IndexDDF value determines the manner in which the Btrieve external ISAM database is to handle the INDEX.ddf file, which is updated whenever indexes are created or deleted.

Valid settings are:

  • Require Index.ddf file is required in the database directory, in addition to File.ddf and Field.ddf.

  • Maintain Updates the Index.ddf file if it exists, but does not generate an error if it does not.

  • Ignore Makes no attempt to update the Index.ddf file, regardless of whether or not it exists.


Invalid DataCodePage option in initialization setting. (Error 3337)

The DataCodePage setting for the external data source you are attempting to use is not valid. This setting is in the corresponding \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engine\ <external data source ISAM> in the Windows Registry.

Valid settings are:

  • OEM Data is stored as OEM data; OemToAnsi and AnsiToOem conversions are done.

  • ANSI Data is stored as ANSI data; OemToAnsi and AnsiToOem conversions are not done.


Btrieve: Xtrieve options aren't correct in initialization setting. (Error 3338)

One or more of the XTRPATH, XTRENV, and XTRPINDX settings in the Windows Registry is invalid.

Possible causes and solutions:

  • XTRPATH is the directory search path for locating data files. The format for this entry is:

    XTRPATH=dir1;dir2;dir2

    where dir1, dir2, and dir3 are full directory paths (for example, XTRPATH=C:\DATA;D:\FILES;E:\DATA).

  • XTRENV is the directory and file name for the Xtrieve environment file (for example, XTRENV=C:\XTRV\XTRIEVE.env).

  • XTRPINDX is a pointer to the directory in which to create new Xtrieve tables, expressed as a numeric value corresponding to a directory in XTRPATH, with the first directory having an XTRPINDX of 1, the second having an XTRPINDX of 2, and so on. In the XTRPATH shown previously, an XTRPINDX value of 2 indicates create new Xtrieve tables in the directory D:\FILES.


Btrieve: Invalid IndexDeleteRenumber option in initialization setting. (Error 3339)

The setting for the IndexDeleteRenumber entry in the Btrieve key of the Windows Registry is not valid. The IndexDeleteRenumber entry determines whether remaining indexes are renumbered if one is deleted.

Valid settings are:

  • On Renumbers.

  • Off Does not renumber.

On is consistent with Btrieve version 5.1x behavior. Off is consistent with Btrieve version 6.0 behavior.


Query <name> is corrupt. (Error 3340)

You have referenced an undefined query name. Check the queries listed in the QueryDefs collection to make sure you referenced a valid query name.


The current field must match the join key <name> in the table that serves as the 'one' side of one-to-many relationship. Enter a record in the 'one' side table with the desired key value, and then make the entry with the desired join key in the 'many-only' table. (Error 3341)

You have tried to enter a value into the join field in the many-only table of an outer join with no corresponding value in the join field of the "one" side table. First enter a record in the "one" side table with the desired key value. Then make the entry with the desired join field in the "many-only" table.


Invalid Memo or OLE Object in subquery <name>. (Error 3342)

A subquery cannot return a Memo or OLE Object, and it cannot be compared to a Memo or OLE Object in an expression.


Unrecognized database format <filename>. (Error 3343)

Possible causes:

  • The specified file name is not a Microsoft Jet database.

  • The specified file name is a device name, such as a printer, a console, and so forth.

  • The .mdb file has invalid header information or an unknown sort order.

  • A commit is pending from another user, but the lock file cannot be found.

  • During a commit, you are attempting to write a Long value larger than the 2K maximum page size.

  • The database is damaged. Repair and compact the database, and then try opening it again.


The database engine does not recognize either the field <name> in a validation expression, or the default value in the table <name>. (Error 3344)

Your expression refers to a field incorrectly or to a field that does not exist. Check to make sure the field name is valid and spelled correctly.


Unknown or invalid field reference <name>. (Error 3345)

Your expression refers to a field incorrectly or to a field that does not exist. Check to make sure the field name is correct.


Number of query values and destination fields aren't the same. (Error 3346)

The INSERT INTO (append) query either does not have enough destination fields or it has more fields in the VALUES or SELECT list than there are fields in the destination table. Select a matching number of fields.


Numeric field overflow. (Error 3349)

The data in a Btrieve field is too large to represent in your application.


Object is invalid for operation. (Error 3350)

You used the RefreshLink method on an object other than a linked table. An object ceases to exist when it is destroyed and when its associated DAO object is closed or is no longer defined in the current scope.


The ORDER BY expression <expression> includes fields that aren't selected by the query. Only those fields requested in the first query can be included in an ORDER BY expression. (Error 3351)

In a union query, you have included fields in an ORDER BY expression that are not specified by the query. Only those fields requested in the first query can be included in an ORDER BY expression.


No destination field name in INSERT INTO statement <statement>. (Error 3352)

The destination field name or names cannot be determined from the expression in the SELECT clause of the INSERT INTO statement.


Btrieve: Can't find file Field.ddf. (Error 3353)

The Btrieve driver cannot find the Field.ddf file pointed to by the File.ddf file.

Possible solutions:

  • If the Field.ddf file exists, fix the reference to it in the File.ddf file using either Novell Xtrieve or another .ddf file builder.

  • If the Field.ddf file doesn't exist, create it using either Novell Xtrieve or another .ddf file builder.


At most one record can be returned by this subquery. (Error 3354)

A subquery of this kind cannot return more than one record. Revise the SELECT statement of the subquery to request only one record.


Syntax error in default value. (Error 3355)

Possible causes:

  • An unknown function name was included in the default value expression in a table-level validation rule.

  • A default value expression in a table-level validation rule is syntactically incorrect.


You attempted to open a database that is already opened exclusively by user <name> on machine <name>. Try again when the database is available. (Error 3356)

Possible causes:

  • You attempted to open a database that is already opened exclusively by the specified user <name>. You cannot open the database until the other user closes it.

  • You attempted to open exclusively a database that is already open in shared (non-exclusive) mode by the specified user <name>. You can open the database only in shared mode until the other user closes it.


This query is not a properly formed data-definition query. (Error 3357)


Can't open the Microsoft Jet engine workgroup information file. (Error 3358)

You attempted to perform a security-related task, but the workgroup information file (typically System.mdw) required for the task cannot be found.


Pass-through query must contain at least one character. (Error 3359)

The SQL string of a pass-through query must contain at least one character.


Query is too complex. (Error 3360)

The query is too complex. Reduce the number of fields in the SELECT clause or the number of subqueries or tables in the join.


Unions not allowed in a subquery. (Error 3361)

You cannot use a UNION operation in a subquery expression. To use a union query in a subquery, first create the union query and save it as a named query. Then include the name of the saved query in your subquery expression.


Single-row update/delete affected more than one row of a linked table. Unique index contains duplicate values. (Error 3362)

Your update or delete query affected more than one record in the linked SQL table. An update and delete query can affect only one record at a time.


Can't use Memo or OLE Object field <name> in the SELECT clause of a union query. (Error 3364)

A field you specified in the SELECT part of a union query in the SQL statement for the query has a field data type of Memo or OLE object. You cannot specify a field of either of these types.


Can't set this property for remote objects. (Error 3365)

This property is not available for objects associated with ODBC databases.


Can't append a relation with no fields defined. (Error 3366)

You are trying to append a CdbRelation object to a Relations collection, but the CdbRelation object has no fields.

To correctly append a Relation

  1. Use the CreateRelation method to create the Relation object.

  2. Set the Table, ForeignTable, and Attributes properties of the Relation object, if you did not specify them as arguments to the CreateRelation method.

  3. Set the Table, ForeignTable, and Attributes properties of the Relation object, if you did not specify them as arguments to the CreateRelation method. Set the Name (if you did not specify it as an argument to the CreateField method) and ForeignName properties of the Field object or objects to the corresponding Name property settings of the primary key and the foreign key Field objects of each field in the relationship.

  4. Use the Append method to save the Field object or objects in the Fields collection of the Relation object.

  5. Use the Append method to save the Relation object in the Relations collection of the database.


Can't append. An object with that name already exists in the collection. (Error 3367)

You tried to append an object to a collection that already contains an object of the same name. Use the Refresh method on the collection and check to see whether the object you want to append already exists, or try changing the object's Name property setting.


Relationship must be on the same number of fields with the same data types. (Error 3368)

The CONSTRAINT clause you are using to create a relationship includes a different number of fields for each table or includes fields with different data types. Check the number of fields in the CONSTRAINT clause, check the data types of fields to make sure they match, and try again.


Can't modify the design of table <name>. It's in a read-only database. (Error 3370)

You cannot modify tables in a read-only database.


Can't find table or constraint. (Error 3371)

The table or relationship you specified does not exist. Specify a valid table or constraint name.


No such index <name> on table <name>. (Error 3372)

The specified index does not exist in the specified table. Check your code for a misspelling or other error, or verify the Indexes collection contains the specified index.


Can't create relationship. Referenced table <name> doesn't have a primary key. (Error 3373)

Can't create relationship. Referenced table <name> doesn’t have a primary key. (Error 3373)

The table you have referenced in the CONSTRAINT clause does not have a primary key. To create the relationship, you must either create a primary key in the referenced table, or specifically reference one or more uniquely indexed fields to use in the relationship.


The specified fields are not uniquely indexed in table <name>. (Error 3374)


Table <name> already has an index named <name>. (Error 3375)

You are trying to create an index that already exists. You must specify a unique name for each index.


Table <name> doesn't exist. (Error 3376)

Table <name> doesn’t exist. (Error 3376)

The table you specified does not exist. Check to see if the name you specified exists in the TableDefs collection.


No such relationship <name> on table <name>. (Error 3377)

The relationship you specified does not exist in this database. Check to see if the name you specified exists in the Relations collection.


There is already a relationship named <name> in the current database. (Error 3378)

You must specify a unique name for each relationship you add to a database by using data-definition queries. Check to see if the name you specified exists in the Relations collection.


Can't create relationships to enforce referential integrity. Existing data in table <name> violates referential integrity rules in table <name>. (Error 3379)

You are trying to create a relationship using the CONSTRAINT clause of the ALTER TABLE statement, but existing data in the two tables violates referential integrity constraints. For example, there might be records relating to an employee in the related table but no corresponding record for the employee in the primary table.

To create the relationship, you must edit the data so that primary records exist for all related records.


Field <name> already exists in table <name>. (Error 3380)

You have entered the same field name twice. Rewrite your code, giving each field a unique name. You should also check to see if the field name exists in the Fields collection.


There is no field named <name> in table <name>. (Error 3381)

The specified table does not contain the specified field. Check the spelling of the field name. You should also check to see if the field name exists in the Fields collection.


Size of field <name> is too long. (Error 3382)

Text fields in Microsoft FoxPro tables can be no more than 254 characters, and in Microsoft Jet tables, no more than 255 characters. Redefine the size of the field.


Can't delete field <name>. It's part of one or more relationships. (Error 3383)

You are trying to delete a field for which relationships have been defined in the database. To delete the field, you must first delete its relationships.


Can't delete a built-in property. (Error 3384)

You are trying to delete a Property object defined by the Microsoft Jet database engine.

You can delete only user-defined (including application-defined) properties for which you have permission to modify the design, or properties for which this permission is not required.


User-defined properties don't support a Null value. (Error 3385)

User-defined CdbProperty objects cannot be set to Null. Instead, use the Delete method on the property to remove it from its collection.


Property <name> must be set before using this method. (Error 3386)

You attempted to append a new CdbProperty object to a collection without first setting all of the new object's properties: Value, Type, and Name.


Unknown function <name> in validation expression or default value on <name>. (Error 3388)

The function you are referencing is either unknown (because the name is invalid or misspelled) or is a type of function not allowed by the ValidationRule or DefaultValue property. Among the types of functions not allowed are user-defined, SQL aggregate functions.


Query support unavailable. (Error 3389)

You attempted to establish referential integrity on a CdbRelation object of a CdbQueryDef object, which is not supported.

Change the Attributes property setting of the CdbRelation object to dbRelationDontEnforce.


Account name already exists. (Error 3390)

This is a security problem. You tried to establish a user account using a name that already exists. Check the Users collection to see if the user name already exists, or try again using a different user name.


Can't perform join, group, sort, or indexed restriction. A value being searched or sorted on is too long. (Error 3393)

The maximum combined length of fields used to join, group, or sort is 255 bytes. Reduce the number of fields in your join, group, or sort, or use shorter data types and field sizes for the fields.


Can't save property; property is a schema property. (Error 3394)

You tried to set or change a schema property. When you create a new schema property, specify True as the fourth argument to the CreateProperty method in order to set or delete this property.


Can't perform cascading operation. Since related records exist in table <name>, referential integrity rules would be violated. (Error 3396)

The cascade operation you are attempting violates referential integrity rules with the indicated table. Check the values you are attempting to update or delete, and fix them so they comply with the referential integrity rules.


Can't perform cascading operation. There must be a related record in table <name>. (Error 3397)

The cascade operation you are attempting violates a referential integrity rule that requires a related record in the indicated table. Check the values you are attempting to update or delete, and fix them so they comply with the referential integrity rule.


Can't perform cascading operation. It would result in a null key in table <name>. (Error 3398)

The cascade operation you are attempting would result in a Null value in a primary key field in the indicated table, which has been set up not to allow Null values. Check the values you are attempting to update and fix them so they don't result in Null values.


Can't perform cascading operation. It would result in a duplicate key in table <name>. (Error 3399)

The cascade operation you are attempting would result in a duplicate key in the indicated table, which is set up to not allow duplicate primary keys. Check the values you are attempting to update and fix them so they do not result in duplicate keys.


Can't perform cascading operation. It would result in two updates to field <name> in table <name>. (Error 3400)

The cascade operation you are attempting cannot be completed because it would result in two separate updates to the indicated field. Check the values you are attempting to update, and fix them so that either:

  • The field is updated only one time.

    – or

  • If the field is updated more than once, the result of each update to the field is the same.


Can't perform cascading operation. It would cause field <name> to become Null, which is not allowed. (Error 3401)

The cascade operation you are attempting would result in a Null value in the indicated field, which has been set up to not allow Null values. Check the values you are attempting to update and fix them so they don't result in Null values in this field.


Can't perform cascading operation. It would cause field <name> to become a zero-length string, which is not allowed. (Error 3402)

The cascade operation you are attempting would result in a zero-length string in the indicated field, which is set up to not allow zero-length strings. Check the values you are attempting to update and fix them so they don't result in zero-length strings in this field.


Can't perform cascading operation: <validation text>. (Error 3403)

The cascade operation you are attempting would result in invalid data. Check the values you are attempting to update and fix them so they comply with the validation rules.


Can't perform cascading operation. The value entered is prohibited by the validation rule <rule> set for <name>. (Error 3404)

The cascade operation you are attempting would result in an invalid value in the indicated field, as established by the field's validation rule. Check the values you are attempting to update and fix them so they comply with the validation rule.


Error <error text> in validation rule. (Error 3405)

The expression cannot be evaluated correctly for the reason given in the alert. For example, if the error text is "Type Mismatch," the property setting does not match the data type defined for the field.


The expression you're trying to use for the DefaultValue property is invalid because <error text>. Use a valid expression to set this property. (Error 3406)

The expression you are trying to use for the DefaultValue property is invalid. Set the property to a valid expression.


The server's MSysConf table exists, but is in an incorrect format. Contact your system administrator. (Error 3407)

The MSysConf table created on the server to help control communications between the Microsoft Jet database engine and the linked ODBC data source requires a very specific format.


Invalid field definition <name> in definition of index or relationship. (Error 3409)

Possible causes:

  • The field name you have specified might be misspelled. Check the spelling of the field name.

  • The field type you are using is a Memo or OLE Object, which cannot be indexed.


Invalid entry. Can't perform cascading operation in table <name> because the value entered is too large for field <name>. (Error 3411)

You are trying to save a value to a primary key field that is included in a relationship.

To save your changes to this field, the text you enter must be no longer than the field size of the related field that your application is trying to update for you. In this case, the related field has a shorter field size than the field you are updating. To avoid this problem in the future, set the Size property for both of the matching fields to the same value.


Can't perform cascading update on the table because it is currently in use by another user. (Error 3412)

You are trying to save a value into a primary key field that's included in a relationship.

The matching field cannot be updated because of a locking conflict with another user. To save the record, wait until the related table is no longer in use.


Can't perform cascading operation on table <name> because it is currently in use. (Error 3414)

You are trying to save a value to a primary key field that's included in a relationship.

The matching field cannot be updated because you have it open or locked on your computer. To save the record, first close the related table.


Zero-length string is valid only in a Text or Memo field. (Error 3415)

You are trying to enter a zero-length string in a field that has a data type other than Text or Memo. You may be able to enter a Null value instead.


<reserved error alert> (Error 3416)

This error was generated by an application released after this version of the Microsoft Jet database engine. Contact Microsoft AnswerPoint.


An action query cannot be used as a row source. (Error 3417)

Possible cause:

  • The query being used as a record source is an action query or a data-definition query.


Can't open <tablename>. Another user has the table open using a different network control file or locking style. (Error 3418)

The Microsoft Jet database engine cannot open an external Paradox table because of inconsistencies between your initialization settings and those of another user who currently has the table open. The ParadoxNetPath and the ParadoxNetStyle settings in the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Paradox key of the Windows Registry must be consistent for all users sharing a database. Make sure your initialization settings match those of all other users sharing the database, and then try opening the table again.


Can't open this Paradox 4.x or 5.x table because ParadoxNetStyle is set to 3.x in the Windows Registry. (Error 3419)

The Microsoft Jet database engine was unable to open an external Paradox table because of inconsistencies between the version of the table and your ParadoxNetStyle setting in the Windows Registry.

To correct the problem

  1. Exit your application.

  2. Start the Registry Editor, navigate to the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Paradox key, and select the ParadoxNetStyle value.

  3. On the Edit menu, click Modify.

  4. Specify the value 4.x in the Value data box.

    The ParadoxNetStyle setting must be consistent for all users sharing a database.

  5. Restart your application, and then try opening the table again.


Object is invalid or no longer set. (Error 3420)

You are attempting to reference an object that is no longer valid or has not been set.

Possible causes:

  • The object has been closed.

  • The object has been orphaned (the parent object has been closed or deleted).

  • The object is out of scope.

  • The object library is not registered in the Windows Registry.

  • You are trying to reference a method or property of the collection, but you have not assigned it to a variable first. For example, to reference the Name property, use the following:
    Dim dbsPublish As Database
Set dbsPublish = OpenDatabase("BIBLIO.mdb")
dbname = dbsPublish.Name


Data type conversion error. (Error 3421)

The Microsoft Jet database engine was unable to convert data into the type required by a method or property. This problem typically occurs if you use an argument of one type when a method or property expects another type.


Can't modify table structure. Another user has the table open. (Error 3422)

The Microsoft Jet database engine was unable to modify the structure of a table because another user currently has the table open. Wait until the table is closed, and then try making your changes again.


You cannot use ODBC to import from, export to, or link an external Microsoft Jet or ISAM database table to your database. (Error 3423)

You are attempting to link, import data from, or export data to either an external Microsoft Jet table or an external ISAM database table (for example, dBASE, FoxPro, Paradox, or Btrieve), but you have selected <SQL Database> as the data source. Select the appropriate data source for the data you are attempting to link.


Can't create database because the locale is invalid. (Error 3424)

An invalid locale parameter was specified. Make sure you are using a valid Data Access Objects (DAO) constant to specify the locale parameter.


A problem occurred in your database. Correct the problem by repairing and compacting the database. (Error 3428)

The database you are attempting to use has an unspecified problem and, as a result, it is marked as corrupt.

To correct the problem

  6. Close the database.

  7. Repair the database with the RepairDatabase method. In Microsoft Access, you can also do this by going to the Tools menu, pointing to Database Utilities, and then clicking Repair Database.

  8. Compact the database with the CompactDatabase method. In Microsoft Access, you can also do this by going to the Tools menu, pointing to Database Utilities, and then clicking Compact Database.

Important All steps are required.


Incompatible version of an installable ISAM. (Error 3429)

You attempted to use an older version of an installable ISAM with the current version of the Microsoft Jet database engine. Run Setup again to install the correct version of the installable ISAM.


While loading the Microsoft Excel installable ISAM, OLE was unable to initialize. (Error 3430)

OLE Automation was unable to initialize while loading the Microsoft Excel installable ISAM. Try reinstalling the OLE DLL files.


This is not a Microsoft Excel 5.0 file. (Error 3431)

You attempted to read a file as a Microsoft Excel version 5.0 file, but the file isn't in this format.


Error opening a Microsoft Excel 5.0 file. (Error 3432)

An OLE error occurred while opening a Microsoft Excel version 5.0 file.


Invalid setting in Excel key of the Engines section of the Windows Registry. (Error 3433)

One of the settings in the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.5\Engines\Excel key of the Windows Registry is not valid. Edit the Windows Registry to be sure all the parameters are valid.


Can't expand named range. (Error 3434)

Cells with values were encountered while attempting to add rows to a Microsoft Excel version 5.0 named range. These cells cannot be overwritten by an append operation.


Cannot delete spreadsheet cells. (Error 3435)

Data in the specified spreadsheet range of cells cannot be deleted. These cells may contain formulas, or they may be protected cells.


Failure creating file. (Error 3436)

An error occurred while attempting to create a Microsoft Excel or text file or Lotus installable ISAM.

Possible causes:

  • Insufficient disk space

  • Network failure


Spreadsheet is full. (Error 3437)

You tried to add new records to a Lotus 1-2-3 or Microsoft Excel version 3.0 or version 4.0 file, but the file is full. Files of these types can hold a maximum of 16,384 records.


The data being exported does not match the format described in the Schema.ini file. (Error 3438)

Make sure the data being exported matches the format described in the Schema.ini file.


You attempted to link or import a Microsoft Word mail merge file. Although you can export such files, you cannot link or import them. (Error 3439)

You attempted to link or import a Microsoft Word mail merge file. Although you can export such files, you cannot link or import them.


An attempt was made to import or link an empty text file. To import or link a text file, the file must contain data. (Error 3440)

You attempted to import or link an empty text file. To import or link a text file, the file must contain data.


Text file specification field separator matches decimal separator or text delimiter. (Error 3441)

Two or more of the following delimiters settings used by the Text ISAM are the same:

  • TxtDelimiter

  • NumberDecimalSymbol

  • CurrencyDecimalSymbol

  • Format


In the text file specification <name>, the <name> option is invalid. (Error 3442)

One of the options in the text file specification for the Text ISAM is invalid.


The fixed-width specification <name> contains no column widths. (Error 3443)

The fixed-width parameter specified in the text file specification for the Text ISAM is invalid. It does not specify a column width.


In the fixed width specification <name>, column <column> does not specify a width. (Error 3444)

No column width parameter is specified in the text file specification for the Text ISAM is invalid.


Incorrect version of the DLL file <name> was found. (Error 3445)

For Microsoft Jet databases, the installed Jet DLL (msajt200.dll for 16-bit versions or msjt2032 for 32-bit versions) must be version 2.5 or later.

For ODBCDirect databases, the installed Remote Data Objects (RDO) DLL (msrdo32.dll) must be version 1.0 or later.

Try reinstalling the application that returned the error.


Jet VBA file (VBAJET.dll for 16-bit versions, or VBAJET32.dll for 32-bit versions) is missing. Try reinstalling the application that returned the error. (Error 3446)

The Jet VBA file (VBAJET.dll for 16-bit versions or VBAJET32.dll for 32-bit versions) could not be found. Try reinstalling the application that returned the error.


The Jet VBA file (VBAJET.dll for 16-bit versions, or VBAJET32.dll for 32-bit versions) failed to initialize when called. Try reinstalling the application that returned the error. (Error 3447)

The Jet VBA file (VBAJET.dll for 16-bit versions or VBAJET32.dll for 32-bit versions) did not initialize when it was called. Try reinstalling the application that returned the error.


A call to an OLE system function was not successful. Try reinstalling the application that returned the error. (Error 3448)

An OLE Automation function called failed. Try reinstalling the application that returned the error.


No country code found in the connection string. (Error 3449)

No country code was found in the connection string.


You can't make changes to the design of the database at this replica. (Error 3452)

Changes to the design of a replicated database can be made only at the Design Master. The replica you are attempting to change is not the Design Master for the replica set. Locate the Design Master and make your changes there.


You can't establish or maintain an enforced relationship between a replicated table and a local table. (Error 3453)

You are attempting to establish or maintain an enforced relationship between a replicated table and a nonreplicated table. Replication does not allow an enforced relationship between:

  • A replicated table and a local table.

  • Two local tables that you are making replicable.

  • Two tables with different KeepLocal property settings.

Delete the relationship between the two tables before proceeding.


Can't make the database replicable. (Error 3455)

The Microsoft Jet database engine was in the process of making the database replicable. The operation failed because there were insufficient resources. Make sure the total number of fields after replication does not exceed 255 in a single table and the total number of bytes in a record does not exceed 2048.


The object named <name> in the <name> collection cannot be made replicable. (Error 3456)

The Microsoft Jet database engine was in the process of making the object replicable. The operation failed because there were insufficient resources to manipulate the object. If the object is a table, make sure the total number of fields after replication does not exceed 255 and the total number of bytes in a record does not exceed 2048. If the number of fields or characters is over the limit, decrease the size of the record.


You can't set the KeepLocal property for an object that is already replicated. (Error 3457)

The KeepLocal property cannot be set on a replicated object. Setting a local object's KeepLocal property after the database has been replicated has no effect on the object. If you want to keep an object from being replicated to the other replicas in the set, set the object's Replicable property to "F".


The KeepLocal property cannot be set on a database; it can be set only on the objects in a database. (Error 3458)

The KeepLocal property is set to "T" for objects in a database that you do not want replicated. You cannot set this property for the entire database.


After a database has been replicated, you cannot remove the replication features from the database. (Error 3459)

You cannot remove the replication features from a database that has been replicated, either by setting its Replicable property to "T" or by converting it with the Windows Briefcase, Microsoft Access, or the Replication Manager. Using DAO to set the database's Replicable property to "F" or any other value has no effect on the replicated database. If you need to use a copy of the database that does not have the properties, fields, tables, and other characteristics associated with replication, open the backup copy of the database made before the database was first converted.


The operation you attempted conflicts with an existing operation involving this member of the replica set. (Error 3460)

Another user or application is already performing the same operation on this member of the replica set. Retry your action later.


The replication property you are attempting to set or delete is read-only and can't be changed. (Error 3461)

Many properties related to replication are for internal use only or are available to the developer on a read-only basis. Review your program code to make sure you are reading rather than changing the property.


Failure to load a DLL. (Error 3462)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Can't find the .dll <name>. (Error 3463)

Make sure that the specified dynamic-link library is in your path or reinstall Replication Manager (or your application).


Data type mismatch in criteria expression. (Error 3464)

The criteria expression in a Find method is attempting to compare a field with a value whose data type does not match the field’s data type.


The disk drive you are attempting to access is unreadable. (Error 3465)

If you are attempting to access a floppy disk, make sure the door to the disk drive is closed. If you are attempting to access a hard disk, the disk might have a corrupted sector.


Access was denied while accessing dropbox folder <name>. (Error 3468)

Check your permissions for the dropbox folder.


The disk for dropbox folder <name> is full. (Error 3469)

There is not enough space on the dropbox folder's disk drive to complete the operation. Delete unneeded files from the disk to create sufficient space for the operation.


Disk failure accessing dropbox folder <name>. (Error 3470)

The disk might have a corrupted sector.


Failure to write to the Synchronizer log file. (Error 3471)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Disk full for path <name>. (Error 3472)

Remove files from the disk drive to free up space.


Disk failure while accessing log file <name>. (Error 3473)

The disk drive for the log file may have a bad sector.

To select a different disk drive for the log file, open the Replication Manager, and on the Tools menu, click Configure Microsoft Replication Manager. Or run the Setup program for the application using replication.


Can't open the log file <name> for writing. (Error 3474)

Make sure you have permission to write to the log file.


Sharing violation while attempting to open log file <name> in Deny Write mode. (Error 3475)

Close the log file in all other applications.


Invalid dropbox path <name>. (Error 3476)

Make sure the dropbox path is correct.

Open the Replication Manager, go to the Tools menu, and then click Configure Microsoft Replication Manager. Or run the Setup program for the application using replication.


Dropbox address <name> is syntactically invalid. (Error 3477)

Reset your dropbox folder. Open the Replication Manager, go to the Tools menu, and then click Configure Microsoft Replication Manager. Or run the Setup program for the application using replication.


The replica is not a partial replica. (Error 3478)

You are attempting to get information about the filter or some other aspect of a partial replica. However, the replica you are querying is not a partial replica. Use the Replication Manager to view the replica’s property sheet and confirm that the replica is not a partial replica.


Can't designate a partial replica as the Design Master for the replica set. (Error 3479)

Select a different replica to become the Design Master.


The relationship <name> in the partial filter expression is invalid. (Error 3480)

Specify a valid relationship.


The table name <name> in the partial filter expression is invalid. (Error 3481)

Make sure you are using the correct table name in the expression.


The filter expression for the partial replica is invalid. (Error 3482)

The ReplicaFilter property was set to an invalid string.


The password supplied for the dropbox folder <name> is invalid. (Error 3483)

To specify the password, start the Replication Manager. On the Tools menu, click Configure Microsoft Replication Manager, and re-enter the password for the dropbox folder.


The password used by the Synchronizer to write to a destination dropbox folder is invalid. (Error 3484)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The object can't be replicated because the database is not replicated. (Error 3485)

You cannot replicate an object in a database unless you first replicate the database that contains it. You can replicate the database by:

  • Dragging it into the Windows Briefcase.

  • Using DAO programming to set the Replicable property to "T" or the ReplicableBool property to True.

  • Using Microsoft Access.

  • Using the Replication Manager.

All objects in the database are replicated when the database is replicated, unless the KeepLocal property has been set on an object.


You can't add a second Replication ID AutoNumber field to a table. (Error 3486)

The table you are attempting to change already has one field that uses the Replication ID AutoNumber (or GUID) data type. If you are attempting to create a second Replication ID field to serve as a foreign key, use the Number data type instead of the AutoNumber data type.


The database you are attempting to replicate can't be converted. (Error 3487)

Only databases created with version 3.0 or later of the Microsoft Jet database engine can be replicated. Although you can open the database by using an installable ISAM, you cannot convert it to a replicable form. If the database was created by using an earlier version of Microsoft Jet, convert the format to the newer version by going to the Microsoft Access Tools menu, pointing to Database Utilities, and then clicking Convert Database. If the database is in another format, export the data to a new Microsoft Jet database and retry.


The value specified is not a ReplicaID for any member in the replica set. (Error 3488)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The object specified can't be replicated because it is missing a necessary resource. (Error 3489)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Can't create a new replica because the <name> object in <name> container could not be replicated. (Error 3490)

The Microsoft Jet database engine was in the process of creating a replica. The operation failed when it attempted to act on the object and container identified in the error message.


The database must be opened in exclusive mode before it can be replicated. (Error 3491)

You attempted to replicate a database after opening the database in shared mode. Close the database and reopen it in exclusive mode, and then replicate it.


The synchronization failed because a design change could not be applied to one of the replicas. (Error 3492)

The Microsoft Jet database engine attempted to update the database design at one of the replicas. There are several possible reasons why the design could not be updated, including:

  • The object you're trying to update is already open at the replica.

  • You added an enforced relationship to a replica that has a foreign key that references a nonexistent primary key.

For additional information regarding the synchronization failure, look in the MSysSchemaProb table, either at the Design Master or the replica that was the target of the synchronization.


Can't set the specified Registry parameter for the Synchronizer. (Error 3493)

You need to reconfigure the Synchronizer on your computer.

To configure the Synchronizer

  1. Start Replication Manager.

  2. On the Tools menu, click Configure Microsoft Replication Manager.

    Follow the instructions in the wizard.


Unable to retrieve the specified Registry parameter for the Synchronizer. (Error 3494)

You need to reconfigure the Synchronizer on your computer.

To configure the Synchronizer

  3. Start Replication Manager.

  4. On the Tools menu, click Configure Microsoft Replication Manager.

    Follow the instructions in the wizard.


There are no scheduled synchronizations between the two Synchronizers. (Error 3495)

The schedule between two Synchronizers has been deleted or you are attempting to set a schedule between the Synchronizer on your computer and itself. Use the Replication Manager to set the schedule with the correct Synchronizer.


Replication Manager cannot find the ExchangeID in the MSysExchangeLog table. (Error 3496)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Unable to set a schedule for the Synchronizer. (Error 3497)

There was an internal problem setting the schedule. Try again.


Can't retrieve the full path information for a member of the replica set. (Error 3499)

This is an unexpected warning. Please contact Microsoft AnswerPoint for further information.


You cannot specify two different Synchronizers to manage the same replica. (Error 3500)

Use a valid remote Synchronizer ID in your synchronization request.


The Design Master or replica is not being managed by a Synchronizer. (Error 3502)

You are attempting to get information about the Design Master or a replica that is not managed by a Synchronizer.


The Synchronizer's Registry has no value set for the key you queried. (Error 3503)

You need to reconfigure the Synchronizer on your computer.

To configure the Synchronizer

  1. Start Replication Manager.

  2. On the Tools menu, click Configure Microsoft Replication Manager.

    Follow the instructions in the wizard.


The Synchronizer ID does not match an existing ID in the MSysTranspAddress table. (Error 3504)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The Synchronizer is unable to open the Synchronizer log. (Error 3506)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Failure writing to the Synchronizer log. (Error 3507)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


There is no active transport for the Synchronizer. (Error 3508)

You must reconfigure the Replication Manager.

To configure the Synchronizer

  3. Start Replication Manager.

  4. On the Tools menu, click Configure Microsoft Replication Manager.

    Follow the instructions in the wizard.


Could not find a valid transport for this Synchronizer. (Error 3509)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The member of the replica set you are attempting to synchronize is currently being used in another synchronization. (Error 3510)

The Design Master or a replica can be involved in only one synchronization at a time. Although you cannot initiate a second synchronization while the member is locked, you can continue using it. Wait a few minutes and try your synchronization again.


Failed to read the dropbox folder. (Error 3512)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Failed to write to the dropbox folder. (Error 3513)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Synchronizer could not find any scheduled or on-demand synchronizations to process. (Error 3514)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The Microsoft Jet database engine could not read the system clock on your computer. (Error 3515)

The Microsoft Jet database engine uses your computer's system clock for certain internal processes. It tried to read the computer's clock but was not able to. Shut down and restart your computer.


Could not find transport address. (Error 3516)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Synchronizer could not find any messages to process. (Error 3517)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Could not find Synchronizer in the MSysTranspAddress table. (Error 3518)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Failed to send a message. (Error 3519)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The replica name or ID does not match a currently managed member of the replica set. (Error 3520)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Two members of the replica set cannot be synchronized because there is no common point to start the synchronization. (Error 3521)

Too much time has passed since these two members of the replica set were last synchronized. The Microsoft Jet database engine cannot find a common point of reference to begin applying changes in the content or structure of the database.


Synchronizer cannot find the record of a specific synchronization in the MSysExchangeLog table. (Error 3522)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Synchronizer cannot find a specific version number in the MSysSchChange table. (Error 3523)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The history of design changes in the replica does not match the history in the Design Master. (Error 3524)

The Synchronizer is unable to synchronize the two members of the replica set because the history of design (or schema) changes is different for each replica. The discrepancy in design history might be caused by either the existence of two Design Masters or because the Design Master has been restored from a backup made sometime in the past.


Synchronizer could not access the message database. (Error 3525)

The message database is not available for use by the Synchronizer. The database file may be in use by another program or user (users should not open Synchronizer message databases). Close any application that might be using the database.


The name selected for the system object is already in use. (Error 3526)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The Synchronizer or Replication Manager could not find the system object. (Error 3527)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


There is no new data in shared memory for the Synchronizer or Replication Manager to read. (Error 3528)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The Synchronizer or Replication Manager found unread data in the shared memory. The existing data will be overwritten. (Error 3529)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The Synchronizer is already serving a client. (Error 3530)

You are attempting to start a second client of the Synchronizer, but the Synchronizer can have only one client at a time. Identify the application or user that is already using the Synchronizer and close the application.


The wait period for an event has timed out. (Error 3531)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Synchronizer could not be initialized. (Error 3532)

It is not possible to start the Synchronizer. Shut down and restart your computer. If the error persists, reconfigure the Synchronizer.

To configure the Synchronizer

  5. Start Replication Manager.

  6. On the Tools menu, click Configure Microsoft Replication Manager.

    Follow the instructions in the wizard.


The system object used by a process still exists after the process has stopped. (Error 3533)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Synchronizer looked for a system event but did not find one to report to the client. (Error 3534)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Client has asked the Synchronizer to terminate operation. (Error 3535)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Synchronizer received an invalid message for a member of the replica set that it manages. (Error 3536)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Cannot initialize Synchronizer because there are too many applications running. (Error 3538)

There are not enough system resources available to run all the open applications and to start the Synchronizer. Shut down one or more applications and try again.


A system error has occurred or your swap file has reached its limit. (Error 3539)

The Synchronizer has made a system call that resulted in an unexpected problem. Shut down, turn off, and then restart your computer.


Your swap file has reached its limit or is corrupted. (Error 3540)

The Synchronizer has encountered an unexpected system problem. Shut down, turn off, and then restart your computer.


Synchronizer could not be shut down properly and is still active. (Error 3541)

A programmatic request to terminate the Synchronizer was not completed successfully and the Synchronizer is still running in the background.

To terminate the Synchronizer

  7. Press CTRL+ALT+DELETE to display the Close Program dialog box.

  8. Click Synchronizer.

  9. Click End Task.


Process stopped when attempting to terminate Synchronizer client. (Error 3542)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Synchronizer has not been set up. (Error 3543)

The Synchronizer for your computer has not been set up.

To configure the Synchronizer

  10. Start Replication Manager.

  11. On the Tools menu, click Configure Microsoft Replication Manager.

    Follow the instructions in the wizard.

If you are using a third-party application, obtain the Synchronizer Setup disk from the developer supporting your application.


Synchronizer is already running. (Error 3544)

Only one instance of the Synchronizer can operate at a time. Use the currently operating Synchronizer instead of starting a second Synchronizer on this computer.


The two replicas you are attempting to synchronize are from different replica sets. (Error 3545)

Replicas from different replica sets cannot be synchronized. Make sure you have selected the proper replica for synchronization.


The type of synchronization you are attempting is not valid. (Error 3546)

The requested synchronization cannot be performed because of an invalid exchange option in the Synchronize method. Use a valid synchronization type in your program.


Synchronizer could not find a replica from the correct set to complete the synchronization. (Error 3547)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


GUIDs do not match or the requested GUID could not be found. (Error 3548)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The file name you provided is too long. (Error 3549)

Use a shorter file name.


There is no index on the GUID column. (Error 3550)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Unable to delete the specified Registry parameter for the Synchronizer. (Error 3551)

You need to reconfigure the Synchronizer on your computer.

To configure the Synchronizer

  1. Start Replication Manager.

  2. On the Tools menu, click Configure Microsoft Replication Manager.

    Follow the instructions in the wizard.


The size of the Registry parameter exceeds the maximum allowed. (Error 3552)

Each parameter in the Windows Registry has a maximum size. The setting you attempted to use exceeded the allowed maximum. Check the size limitation for the parameter you are setting.


The GUID could not be created. (Error 3553)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


All valid nicknames for replicas are already in use. (Error 3555)

You have reached the maximum number of replicas (32,768) allowed in a replica set. Start a new replica set.


Invalid path for destination dropbox folder. (Error 3556)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Invalid address for destination dropbox folder. (Error 3557)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Disk I/O error at destination dropbox folder. (Error 3558)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Failure to write because destination disk is full. (Error 3559)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The two members of the replica set you are attempting to synchronize have the same ReplicaID. (Error 3560)

Synchronize with a different target member of the replica set.


The two members of the replica set you are attempting to synchronize are both Design Masters. (Error 3561)

Delete one of the Design Masters.


Access denied at destination dropbox folder. (Error 3562)

Check to see if you have permission for the drive where the destination dropbox folder resides.


Fatal error accessing a local dropbox folder. (Error 3563)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Synchronizer can't find the source file for messages. (Error 3564)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


There is a sharing violation in the source dropbox folder because the message database is open in another application. (Error 3565)

Close the message database. Users must not open the message database directly.


Network I/O error. (Error 3566)

The communication between your computer and the network is experiencing a problem. Check to be sure your network is operating properly and that your network cable is tightly connected to your computer. Shut down, turn off, and restart your computer.


Message in dropbox folder belongs to the wrong Synchronizer. (Error 3567)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Synchronizer could not delete a file. (Error 3568)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


This member of the replica set has been logically removed from the set and is no longer available. (Error 3569)

The member of the replica set you are attempting to use has been removed because either it has not been synchronized within the required number of days (retention period) or it has been synchronized with a second Design Master. The member should be deleted from your computer.

If there is data in the member that has not been synchronized with any other member in the replica set, manually enter that data in another member. You can determine which records have unsynchronized data by examining the s_Generation field in each table. A value of 0 in the s_Generation field indicates the record is inserted or updated and has not been synchronized with another replica in the set.


The attempt to set a column in a partial replica violated a rule governing partial replicas. (Error 3571)

You cannot change a primary key of a table in a partial replica unless it has no references to it.


A disk I/O error occurred while reading or writing to the TEMP directory. (Error 3572)

A problem has occurred accessing the TEMP directory on your computer. Check that the path to the TEMP directory is set properly.


The ReplicaID for this member of the replica set was reassigned during a move or copy procedure. (Error 3574)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The disk drive you are attempting to write to is full. (Error 3575)

The disk drive does not have enough space to complete the operation. Delete unneeded files from the disk to create sufficient space for the operation. Make space available on the disk larger than the file you are attempting to save.


The database you are attempting to open is already in use by another application. (Error 3576)

If you are attempting to open the database in exclusive mode, it is possible that another application already has the database open. If you are attempting to open the database in shared mode, it is possible that another application has the database open in exclusive mode. Close the other applications using the database and try your request again.


Can't update replication system column. (Error 3577)

The column you are attempting to update is a system column and is read-only.


Failure to replicate database; can't determine whether the database is open in exclusive mode. (Error 3578)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


Can't open replication system table <name> because the table is already in use. (Error 3581)

The system table needed to complete this operation is already in use. Wait a few minutes and try your operation again.


Cannot make the <name> object in <name> container replicable. (Error 3583)

An object (table, form, report, module, macro) in the indicated container cannot be made replicable.

An example of an object that cannot be made replicable is a table that has 253 or more fields. Since replication needs to add a minimum of 3 additional fields, this would exceed the 255 field limit.


Insufficient memory to complete operation. (Error 3584)

Your computer ran out of memory while trying to replicate the database. Close other applications on the computer and try the operation again.


Syntax error in partial filter expression on table <name>. (Error 3586)

Make sure you are using the correct syntax in the expression.


Invalid expression in the ReplicaFilter property. (Error 3587)

The ReplicaFilter string contains an invalid word. Check the syntax for any misspelled or missing words.


Error when evaluating the partial filter expression. (Error 3588)

This is an unexpected error. Please contact Microsoft AnswerPoint for further information.


The partial filter expression contains an unknown function. (Error 3589)

Make sure you are using the correct name of the function. Also, not all functions are valid in filter expressions.


You can't replicate a password-protected database or set password protection on a replicated database. (Error 3592)

If a database password is set on the database, remove the password.


You can't change the data master attribute for the replica set. (Error 3593)

Whether a replica set allows users to change data at all replicas or only at the Design Master is determined when the database is first converted into a Design Master. After the database has been converted, the single or multiple data master attribute cannot be changed.


You can't change the data master attribute for the replica set. It allows data changes only at the Design Master. (Error 3594)

Whether a replicated database allows users to change data only at the Design Master or at all replicas is determined when the database is first converted into a Design Master. After the database has been converted, the single or multiple data master attribute can't be changed.


The system tables in your replica are no longer reliable and the replica should not be used. (Error 3595)

The replica on your computer is corrupted. When the Microsoft Jet database engine repaired the replica, it may have altered one or more system tables. Delete the replica and replace it with a new replica.


Synchronizing with a non-replicated database is not allowed. The <name> database is not a Design Master or replica. (Error 3605)

You are attempting to synchronize a replicated database with a non-replicated database or to synchronize two nonreplicated databases. Only replicas made from the same replicated database can be synchronized.

If one of the databases has already been replicated, use it to create your second database replica.

If neither database has been replicated, select one of the databases to be used as the Design Master for the replica set. Open that database using Microsoft Access, go to the Tools menu, point to Replication, and click Create Replica. If Microsoft Access is not available but Windows 95 Briefcase is available, drag the database into the Briefcase to create a replica. Do not attempt to replicate the second of the two original databases and then synchronize the two databases. The second database must be a replica of the first for synchronization to succeed.


The replication property you are attempting to delete is read-only and cannot be removed. (Error 3607)

Check to be sure you are deleting the correct property.


Record length is too long for an indexed Paradox table. (Error 3608)

An indexed Paradox table has a maximum record length of 1350 bytes. Try reducing the size of some Text or Memo fields.


No unique index found for the referenced field of the primary table. (Error 3609)

When you create a relationship between tables, the referenced field in the primary table must have a unique index. See the CdbIndex object and Primary property topics for more details on how to do this.


Same table <table> referenced as both the source and destination in a make-table query. (Error 3610)

One of the source tables in a SELECT INTO statement is also named as the destination table. Either remove the table from the source tables or rename the destination table.


Can't execute data definition statements on linked data sources. (Error 3611)

Can’t execute data definition statements on linked data sources. (Error 3611)

The Microsoft Jet database engine cannot create an index on a linked ISAM table, or on an ODBC table that already has a unique index.


Multi-level GROUP BY clause is not allowed in a subquery. (Error 3612)

An SQL subquery cannot list more than one field in a GROUP BY clause.


Can't create a relationship on linked ODBC tables. (Error 3613)

Can’t create a relationship on linked ODBC tables. (Error 3613)

The Microsoft Jet database engine cannot create a relationship on linked tables in ODBC data source tables.


GUID not allowed in Find method criteria expression. (Error 3614)

The criteria expression in a Find method cannot reference a GUID.


Type mismatch in JOIN expression. (Error 3615)

A JOIN expression is attempting to join two tables on fields of incompatible data types. For example, you will get this error if you attempt to join a Memo field with a Text field.


Updating data in a linked table is not supported by this ISAM. (Error 3616)

The installable ISAM you are using does not allow updates to records in external tables. You can only add new records.


Deleting data in a linked table is not supported by this ISAM. (Error 3617)

The installable ISAM you are using does not allow you to delete records in external tables. You can only add new records.


Exceptions table could not be created on import/export. (Error 3618)


Records could not be added to exceptions table. (Error 3619)


The connection for viewing your linked Microsoft Excel worksheet was lost. (Error 3620)


Can't change password on a shared open database. (Error 3621)

Can’t change password on a shared open database. (Error 3621)


You must use the dbSeeChanges option with OpenRecordset when accessing a SQL Server table that has an IDENTITY column. (Error 3622)


Cannot access the FoxPro 3.0 bound DBF file <filename>. (Error 3623)

You tried to access Microsoft Visual FoxPro version 3.0 bound .dbf file. Bound files are accessible only through the FoxPro database container they are bound to.


Couldn't read the record; currently locked by another user. (Error 3624)

Couldn’t read the record; currently locked by another user. (Error 3624)

You tried to read a record on a 2K database page that is currently locked by another user. Wait for the other user to finish working with the record, and then try the operation again.


The text file specification <name> does not exist. You can't import, export, or link using the specification. (Error 3625)

The text file specification <name> does not exist. You can’t import, export, or link using the specification. (Error 3625)


The operation failed. There are too many indexes on table <name>. Delete some of the indexes on the table and try the operation again. (Error 3626)

A table in a Microsoft Jet database can have no more than 32 indexes. You cannot create additional indexes on a table with this many indexes. Further, you cannot compact a database containing a table with this many indexes because compacting a database involves creating several new indexes.

Delete one or more indexes from the named table and try the operation again.


Cannot find the executable file for the Synchronizer (mstran35.exe). (Error 3627)

You are trying to start the Synchronizer and the file Mstran35.exe cannot be found on the specified path.


Partner replica is not managed by a Synchronizer. (Error 3628)

You are trying to synchronize with a partner replica that is not being managed by a Synchronizer.


This synchronizer and synchronizer <name> have the same File System dropbox - <name> (Error 3629)

This Synchronizer and Synchronizer <name> have the same File System dropbox – <name> (Error 3629)

Each Synchronizer should have a unique file system dropbox. Using the same dropbox location for multiple Synchronizers can result in lost messages and incomplete exchanges.


Invalid table name in filter. (Error 3631)

You have referred to a table in a Boolean filter that is not valid. Boolean filters can only refer to the table that is being filtered.


Remote Synchronizer is not configured for remote synchronization. (Error 3632)

This remote Synchronizer is not configured to perform remote synchronization.


Can't load DLL <name>. (Error 3633)

The specified DLL is either not registered or not in the path.


Cannot create a replica using a partial replica. (Error 3634)

You are attempting to create a replica using a partial replica as the source. Partial replicas cannot be replicated.


Cannot create partial replica of a workgroup information file. (Error 3635)

You are attempting to create a partial replica using a workgroup information file as the source. Workgroup information files cannot be replicated.


Cannot populate the replica or change the replica's filter because the replica has conflicts or data errors. (Error 3636)

You are attempting to change a partial replica's filter or populate a partial replica, and that replica has conflicts or data errors. You need to resolve the conflicts or errors before proceeding. This prevents inadvertent loss of conflict information and ensures that errors are corrected properly.


Cannot use the crosstab of a non-fixed column as a subquery. (Error 3637)

You have attempted to sort on a variable column crosstab. You should save the results of the query, and then sort the results with the Sort Ascending or Sort Descending button.


You cannot make a database replicable that is being used by a program that controls modification. (Error 3638)

The database you are trying to replicate is controlled by a database program that does not support replication. To be able to make the database replicable you must ensure it is not being controlled by the source control program.


Cannot create a replica of a workgroup information file. (Error 3639)

You are attempting to replicate a workgroup information file. This is not allowed.


The fetch buffer was too small for the amount of data you requested. (Error 3640)

When performing a GetRows or GetRowsEx method, the fetch buffer was too small to contain the specified rows.


There are fewer records remaining in the Recordset than you requested. (Error 3641)

The end of the CdbRecordset has been reached.


A cancel was performed on the operation. (Error 3642)

A query has been interrupted by the data source. Some of the matching rows have not been returned. Try submitting the query again.


One of the records in the Recordset was deleted by another process. (Error 3643)

One or more of the records in the CdbRecordset was deleted after the query was performed. Refresh the CdbRecordset and try the query again.


One of the binding parameters is incorrect. (Error 3645)

A data type or binding type in the binding structure passed to GetRows or GetRowsEx was an invalid value, or the maximum field length is invalid for the indicated data type. Check your binding structure.


The specified row length is shorter than the sum of the column lengths. (Error 3646)

The row length parameter did not specify enough space for the column binding.


A column requested is not being returned to the Recordset. (Error 3647)

One of the requested columns is not available.


Cannot synchronize a partial replica with another partial replica. (Error 3648)

The database you are trying to synchronize with is a partial replica. You cannot synchronize a partial replica with another partial replica, because the other partial replica may not contain all records that satisfy your partial replica's filter.


The language-specific code page was not specified or could not be found. (Error 3649)

You have attempted to open a database that was created with a language that is not installed on your computer. You should determine what language was specified for this database when it was created and then make sure that language is installed on your system. If the database was created with DAO, the language was specified with the collating order argument of the CreateDatabase method.

Languages can be added to your system through the Regional settings of the Control Panel.


Internet is too slow. (Error 3650)

There has been a failure due to Internet transmission speed.


Invalid Internet address. (Error 3651)

You have requested an Internet address which is not valid or not available. Check the address, and if it is valid, try again later.


Internet login failure. (Error 3652)

The server did not recognize the login information you entered.


Internet not set up. (Error 3653)

There is a problem with the Internet setup.


Error in evaluating a partial expression. (Error 3656)

You have entered an invalid expression in a Boolean filter used to determine which records to use in a partial replica. The replica filter can take the following values:

Value | Description
A string | A criteria that a record must satisfy in order to appear in the replicated table. The string is similar to an SQL WHERE clause, but you cannot specify subqueries, aggregate functions (such as Count), or user-defined functions within the criteria.
True | Replicate all records.
False | (Default) Do not replicate any records.


Requested exchange failed because <description>. (Error 3660)

Please look in the exchange history for more details on why the exchange failed. If you are using Replication Manager, you can view the exchange history by right-clicking on the replicated object. You can also view the replication history with the Synchronization History command on the View menu.

If you are conducting replication with Microsoft Access, you can open the exchange history table in Datasheet view to see the exchange history. The exchange history table is a hidden object. Display it in the Database window by selecting the System Objects check box on the View tab of the Options dialog box, which is available by clicking Options on the Tools menu.


action query <DAO definition>

action query

A query that copies or changes data. Action queries include append, delete, make-table, and update queries. Delete and update queries change existing data; append and make-table queries copy existing data. In contrast, select queries return data records. An SQL pass-through query may also be an action query.


ActiveX object <DAO definition>

ActiveX object

An object that is exposed to other applications or programming tools through Automation (formerly OLE Automation) interfaces. For example, Microsoft Access can create and manipulate ActiveX objects within Microsoft Word or Microsoft Excel.


aggregate function <DAO definition>

aggregate function

A function, such as Sum, Count, Avg, and Var, that you can use to calculate totals. In writing expressions and in programming, you can use SQL aggregate functions (including the four listed here) and domain aggregate functions to determine various statistics.


alias <DAO definition>

alias

Microsoft Visual Basic: An alternate name you give to an external procedure to avoid conflict with a Visual Basic keyword, public variable, constant, or a name not allowed by the Visual Basic naming conventions.

Structured Query Language (SQL): An alternate name you give to a field or expression in a SELECT statement (using the AS clause).


ANSI character set <DAO definition>

ANSI character set

An 8-bit character set used by Microsoft Windows that allows you to represent up to 256 characters (0 through 255) using your keyboard. The ASCII character set is a subset of the ANSI set.


append query <DAO definition>

append query

An action query that adds new records to the end of an existing table or query. Append queries don't return records (rows).


argument <DAO definition>

argument

A constant, variable, or expression that supplies additional information to an action, procedure, or method. You use an argument with an operand in an expression to supply additional information required by some action.


array <DAO definition>

array

A variable that contains a finite number of elements that have a common name and data type. Each element of an array is identified by a unique index number. Changes made to one element of an array do not affect the other elements.


ASCII character set <DAO definition>

ASCII character set

American Standard Code for Information Interchange (ASCII) 7-bit character set widely used to represent letters and symbols found on a standard U.S. keyboard. The ASCII character set is the same as the first 128 characters (0 – 127) in the ANSI character set.


asterisk <DAO definition>

asterisk

A character (*) used as a wildcard in SQL LIKE expressions to accept any string of characters. For example, the expression LIKE "*town*" returns records containing the string "town" followed by zero or more characters.

When you create a query or enter an SQL statement, use the asterisk to include all the fields that currently exist in the underlying table or query. For example, SELECT * FROM MyTable returns all fields (columns) from the table.


asynchronous query <DAO definition>

asynchronous query

A type of query in which SQL queries return immediately, even though the results are still pending. This enables an application to continue with other processing while the query is pending completion.


AutoNumber data type <DAO definition>

AutoNumber data type

A field attribute that automatically stores a unique number for each record as it's added to a table. An AutoNumber field uses the Long data type and has its Attributes property set to dbAutoIncrement. Numbers generated by an AutoNumber field can't be modified. (Also known as a Counter.)

Note For replicated tables in replicated databases, an AutoNumber field is not incremented by 1. Instead, it is assigned a random value between -2,000,000,000 and 2,000,000,000.


AutoNumber field <DAO definition>

AutoNumber field

A field data type that automatically stores a unique number for each record as it's added to a table. An AutoNumber field always uses the Long data type, and numbers generated by an AutoNumber field can't be modified. (Also known as a Counter field.)


base computer <DAO definition>

base computer

A computer used in a star topology. A replica is copied from the hub server and placed on the base computer. This replica can be used to make additional replicas for other computers. See also hub server, star topology.


base table <DAO definition>

base table

A table in a Microsoft Jet database. A table defines the structure of a relational database, and is an object that stores data in records and fields. You can manipulate the structure of a base table by using the DAO objects or data definition SQL statements, and you can modify data in a base table by using Recordset objects or action queries.


batch optimistic updating <DAO definition>

batch update

A cursor model for clients that work with cursors but don't hold locks on the server or issue updates by row. Instead, the client updates many rows that are buffered locally, and then it issues a batch update. This cursor model also allows the client to drop the connection to the server and re-establish it with the same server or even a different server.

To use batch updating in DAO 3.5, you must use an ODBCDirect workspace, the DefaultCursorDriver property must be set to dbUseClientBatchCursor at the time the Connection is opened, and the Recordset must be opened with the OpenRecordset method's locktype argument set to dbOptimisticBatch.


Big Integer data type <DAO definition>

Big Integer data type

A data type that stores a signed, exact numeric value with precision 19 (signed) or 20 (unsigned), scale 0 (signed: -263 ≤ n ≤ 263-1, unsigned: 0 ≤ n ≤ 264-1).


binary data type <DAO definition>

binary data type

A data type that stores fixed-length binary data. The maximum length is 255 bytes.


bookmark <DAO definition>

bookmark

A property of the Recordset object that contains a binary string identifying the current record. If you assign the Bookmark value to a variable and then move to another record, you can make the earlier record current again by setting the Bookmark property to that string variable.


Boolean data type <DAO definition>

Boolean data type

A True/False or yes/no value. Boolean values are usually stored in Bit fields in a Microsoft Jet database; however, some databases don't support this data type directly.


Boolean expression <DAO definition>

Boolean expression

An expression that evaluates to either True or False.


byte data type <DAO definition>

byte data type

A fundamental data type used to hold small positive integer numbers ranging from 0 to 255.


Cartesian product <DAO definition>

Cartesian product

The result of joining two relational tables, producing all possible ordered combinations of rows from the first table with all rows from the second table.

Generally, a Cartesian product results from executing an SQL SELECT statement referencing two or more tables in the FROM clause and not including a WHERE or JOIN clause that indicates how the tables are to be joined.


cascade <DAO definition>

cascade

The process of one action triggering another action. For example, when a cascading update relationship is defined for two (or more) tables, an update to the primary key in the primary table automatically triggers (cascades) changes to the foreign table.


cascading delete <DAO definition>

cascading delete

For relationships that enforce referential integrity between tables, an option that causes the deletion of a record from the primary table to automatically delete all related records in the related foreign table or tables.

For example, suppose you establish a relationship between a Customers (primary) table and an Orders (foreign) table with the cascading delete option enabled. When a record in the Customers table is deleted, all orders associated with that customer would also be deleted in the foreign Orders table.


cascading update <DAO definition>

cascading update

For relationships enforcing referential integrity between tables, an option that causes a change to the primary key in a record in the primary table to automatically update the foreign key in all related records in the related foreign table or tables.

For example, suppose you establish a relationship between a Customers (primary) table and an Orders (foreign) table with the cascading update option enabled. When the primary key in a record in the Customers table is changed, all orders associated with that customer would also be changed in the foreign Orders table.


case-sensitive <DAO definition>

case-sensitive

Capable of distinguishing between uppercase and lowercase letters. A case-sensitive search finds only text that is an exact match of uppercase and lowercase letters. Such a search would, for instance, treat “ZeroLengthStr” and “zerolengthstr” as different. Microsoft Jet database operations are not case-sensitive. However, case sensitivity is a feature of some other database management systems.


Char data type <DAO definition>

Char data type

A data type that stores a fixed-length character string. The length is set by the Size property.


class <DAO definition>

class

The formal definition of an object. The class acts as the template from which an instance of an object is created at run time. The class defines the properties of the object and the methods used to control the object's behavior.


client batch cursor library <DAO definition>

client batch cursor library

A library that provides client-side cursor support for ODBCDirect database applications. This library supports all four types of cursors (keyset, static, dynamic, and forward-only) and provides a number of other features including the ability to dissociate connections and perform optimistic batch updates.


clustered index <DAO definition>

clustered index

The physical order of rows is the same as the indexed order of rows.


collection <DAO definition>

collection

An object that contains a set of related objects. An object's position in the collection can change whenever a change occurs in the collection; therefore, the position of any specific object in the collection may vary.


collision <DAO definition>

collision

A conflict that occurs during a batch update.

A collision occurs when a client reads data from the server and then attempts to modify that data in a batch update, but before the update attempt is actually executed another client changes the original server data. In this situation, the first client is attempting to modify server data without knowing what data actually exists on the server.


column <DAO definition>

column

The visual representation of a field in a grid. A column defines the data type, size, and other attributes of one field of a row (record) of data. All columns taken as a set define a row (record) in the database. An individual column contains data related in type and purpose throughout the table; that is, a column's definition does not change from row to row.


commit <DAO definition>

commit

To accept a pending transaction. If you use transaction processing and begin a transaction using DAO, none of the changes made in the transaction are written to the database until you commit or accept the transaction.


compound query <DAO definition>

compound query

A query that is composed of at least one action query (a query that copies or changes data) and at least one select query (a query that returns a Recordset without changing data). In DAO, a compound query is created by putting two or more SQL statements (separated by semicolons) in the SQL property of a QueryDef object.


conflict table <DAO definition>

conflict table

A table that is generated when a synchronization conflict occurs between two replicas. The conflict table appears only in the replica with rejected changes.


connection string <DAO definition>

connection string

A string used to define the source of data for an external database. The connection string is usually assigned to the Connect property of a QueryDef, TableDef, Connection, or Database object or as an argument to the OpenDatabase method.


consistent <DAO definition>

consistent

The state of a multiple-table Recordset object that allows you to perform only updates that result in a consistent view of the data. For example, in a Recordset that is a join of two or more tables (a one-to-many relationship), a consistent query would not allow you to set the many-side key to a value that is not in the one-side table.


constant <DAO definition>

constant

A named item that retains a constant value throughout the execution of a program, as opposed to a variable, whose value can change during execution. Each host application can define its own set of constants. Additional constants may be defined by the user with the Const statement. Constants can be used anywhere in your code in place of actual values. A constant may be a string or numeric literal, another constant, or any combination that includes arithmetic or logical operators except the Is statement and exponentiation. For example:

Const strdb = "c:\Program Files\Microsoft Office\Access\Samples\Northwind.mdb"


constraint <DAO definition>

constraint

A limitation of the possible values that users can enter into a field.


control character<DAO definition>

control character

Any key combination that begins with the CTRL or ESC key.


copy buffer <DAO definition>

copy buffer

A location created by the Microsoft Jet database engine for the contents of a record that is open for editing. The Edit method copies the current record to the copy buffer; the AddNew method clears the buffer for a new record and sets the default values; and the Update method saves the data from the copy buffer to the database, replacing the current record or inserting the new record. Any statement that resets or moves the current record pointer discards the copy buffer. For example, using the MoveNext method or changing the Index property of a table would discard the contents of the copy buffer.


criteria <DAO definition>

criteria

A set of limiting conditions, such as = "Denmark" (meaning equal to Denmark) or > 30000, used in creating a query or filter to show a specific set of records.


crosstab query <DAO definition>

crosstab query

A query that calculates a sum, average, count, or other type of total on records, and then groups the result by two types of information — one down the left side of a grid (row headings) and the other across the top (column headings). For example, the Quarterly Orders by Product query in the Northwind sample database is a crosstab query.


current database <DAO definition>

current database

The Database object returned by the CurrentDB( ) function. A reference of DBEngine.Workspaces(0).Databases(0) returns the first database opened. This concept applies only to Microsoft Access.


Currency data type <DAO definition>

Currency data type

A data type that is useful for calculations involving money or for fixed-point calculations in which accuracy is extremely important. This data type is used to store numbers with up to 15 digits to the left of the decimal point and 4 digits to the right. Because the Currency data type uses discrete values for all amounts, binary round-off isn’t a factor when calculating totals.


current index <DAO definition>

current index

For an indexed table-type Recordset object, the index most recently set with the Index property. This index is the basis for ordering records in a table-type Recordset, and is used by the Seek method to locate records. A Recordset object can have more than one index but can use only one index at a time (although a TableDef object may have several indexes defined on it). The Microsoft Jet database engine may use more than one index to evaluate a query.


current record <DAO definition>

current record

The record in a Recordset object that you can use to modify or examine data. Use the Move methods to reposition the current record in a recordset. Use the Find methods (with a dynaset- or snapshot-type Recordset object) or the Seek method (with a table-type Recordset object) to change the current record position according to specific criteria.

Only one record in a Recordset can be the current record; however, a Recordset may have no current record. For example, after a dynaset-type Recordset record has been deleted, or when a Recordset has no records, the current record is undefined. In this case, operations that refer to the current record result in a trappable error.


current transaction <DAO definition>

current transaction

All changes made to a Recordset object after you use the last BeginTrans method and before you use the Rollback or CommitTrans method.


data access object <DAO definition>

DAO object

An object that is defined by the Data Access Objects (DAO) library. You can use DAO objects, such as the Database, TableDef, Recordset, and QueryDef objects, to represent objects that are used to organize and manipulate data, such as tables and queries, in code.


Data Access Objects (DAO) <DAO definition>

Data Access Objects (DAO)

A programming interface to access and manipulate database objects.


database engine <DAO definition>

database engine

That part of the database system that retrieves data from and stores data in user and system databases.


database replication <DAO definition>

database replication

The process of reproducing a database so that two or more copies (replicas) of the same database can stay synchronized. Changes to the data in a replicated table in one replica are sent and applied to the other replicas in the replica set. Changes made to the design of the database in the Design Master are sent and applied to all replicas in the set.


data-definition query <DAO definition>

data-definition query

An SQL-specific query that can create, alter, or delete a table, or create or delete an index in a database.


data pipelining <DAO definition>

data pipelining

A process that uses batch optimistic updating to cache server data in a local cursor, close the server connection, open a new connection to another server with the same information schema, and then store the data on the new server.


data source <DAO definition>

data source

A named Open Database Connectivity (ODBC) resource that specifies the location, driver type, and other parameters needed by an ODBC driver to access an ODBC database. A data source can be any source of database information.


data type <DAO definition>

data type

The characteristics of a variable that determine what kind of data the variable can hold. Data types include Big Integer, Binary, Byte, Boolean, Char, Currency, Date, Decimal, Double, Float, GUID, Integer, Long, Long Binary (OLE Object), Memo, Numeric, Single, String, Text, Time, TimeStamp, VarBinary, Variant (default), user-defined types (created with the Type statement), and object data types, which include host-defined object data types and DAO object types.


date literal <DAO definition>

date literal

Any sequence of characters with a valid format that is surrounded by number signs (#). Valid formats include the date format specified by the locale settings for your code or the universal date format.

For example, #12/31/92# is the date literal that represents December 31, 1992 where English-U.S. is the locale setting for your application. Use date literals to maximize portability across national languages.


dates and times <DAO definition>

dates and times

Stored internally as different parts of a real number.

The value to the left of the decimal represents a date between December 30, 1899 and December 30, 9999, inclusive. Negative values represent dates prior to December 30, 1899.

The value to the right of the decimal represents a time between 0:00:00 and 23:59:59, inclusive. Midday is represented by .5.


Decimal data type <DAO definition>

Decimal data type

A data type that stores a signed, exact numeric value with precision p and scale s (1 ≤ p ≤15; 0 ≤ s ≤ p).


DDL (Data Definition Language) <DAO definition>

DDL (Data Definition Language)

The language used to describe attributes of a database, especially tables, fields, indexes, and storage strategy.


default synchronization partner <DAO definition>

default synchronization partner

A Synchronizer that is used to automatically synchronize a replica with other replicas in the set. When a replica is created, the Synchronizer managing the source replica becomes the default synchronization partner for the new replica.


default synchronization schedule <DAO definition>

default synchronization schedule

A template used by a Synchronizer to define a schedule between a newly managed replica and its default synchronization partner, when the newly managed replica has no existing synchronization schedule. Once the schedule is defined, you can change the schedule.


default workspace <DAO definition>

default workspace

The Workspace object that DAO automatically establishes when your application first references any DAO object. This Workspace is referenced by DBEngine.Workspaces(0) or simply Workspaces(0).


delete query <DAO definition>

delete query

An action query that deletes a set of rows that match the criteria you specify. A delete query doesn’t return rows.


Design Master <DAO definition>

Design Master

A database to which system tables, system fields, and replication properties have been added. A Design Master is the first replica in a replica set. You can make changes to the database structure only with the Design Master. Replicas in the same replica set can take turns being the Design Master, but there can be only one Design Master at a time in each replica set.


design time <DAO definition>

design time

The time during which you build an application in the development environment by adding controls, setting control or form properties, and so on. In contrast, during run time, you interact with the application as a user would.


destination field <DAO definition>

destination field

A field in a query that will contain the results of your query.


direct synchronization <DAO definition>

direct synchronization

A type of synchronization that occurs when the two replicas can be opened simultaneously during the synchronization process.


DLL (dynamic-link library) <DAO definition>

DLL (dynamic-link library)

A set of routines that can be called from procedures and are loaded and linked into your application at run time.


Double data type <DAO definition>

Double data type

A fundamental data type that holds double-precision floating-point numbers in IEEE format. A Double variable is stored as a 64-bit (8-byte) number ranging in value from -1.79769313486231E308 to -4.94065645841247E-324 for negative values, from 4.94065645841247E-324 to 1.79769313486231E308 for positive values, and 0.


dropbox folder <DAO definition>

dropbox folder

The shared network location where a Synchronizer can leave or pick up design and data changes.


dynamic cursor <DAO definition>

dynamic cursor

A dynamic set of rows that you can use to add, change, or delete rows from an underlying database table or tables. A dynamic cursor can contain columns from one or more tables in a database. Membership is not fixed.


dynaset <DAO definition>

dynaset

A type of Recordset object that returns a dynamic set of pointers to live database data. Like a table- or a snapshot-type Recordset, a dynaset returns data in records (rows) and fields (columns). Unlike a table-type Recordset, a dynaset-type Recordset can be the result of a query that joins two or more tables. The records in a dynaset-type Recordset object are updatable if the Updatable property of the Recordset is True, the Field being changed is updatable, and the data page containing the current record isn’t locked. The data page is locked when the Update method is used (when the LockEdits property is False), or the Edit method is used (when the LockEdits property is True).


equi-join <DAO definition>

equi-join

A join in which records from two tables are combined and added to the Recordset object only when there are equal values in the joined fields.


exclusive <DAO definition>

exclusive

A type of access that protects data in a database shared over a network. When you open a database in exclusive mode, you prevent others from opening the database.


expression <DAO definition>

expression

Any combination of operators, constants, literal values, functions, and names of fields, controls, and properties that evaluates to a single value. You can use expressions as settings for many properties and action arguments, to set criteria, or to define calculated fields in queries.


external database <DAO definition>

external database

Either an ODBC database such as Microsoft SQL Server that resides on a remote server, or one of the external databases such as Paradox, dBASE, Microsoft FoxPro, Microsoft Excel, Microsoft Access, Lotus 1-2-3, HTML, and Text.


external table <DAO definition>

external table

A table in a database outside the open Microsoft Jet database. An external table may take the form of another file or it may be a table in another relational database.


field <DAO definition>

field

A category of information stored in a table in a database — a column of data. An element of a database table that contains a specific item of information, such as last name.


field data types <DAO definition>

field data types

The following table lists the Field data types.

DAO Field data type | Constant
Big Integer | dbBigInt
Binary | dbBinary
Boolean | dbBoolean
Byte | dbByte
Char | dbChar
Currency | dbCurrency
Date/Time | dbDate
Decimal | dbDecimal
Double | dbDouble
Float | dbFloat
GUID | dbGUID
Integer | dbInteger
Long | dbLong
Long Binary (OLE Object) | dbLongBinary
Memo | dbMemo
Numeric | dbNumeric
Single | dbSingle
Text | dbText
Time | dbTime
TimeStamp | dbTimeStamp
VarBinary | dbVarBinary


field properties <DAO definition>

field properties

Attributes of a field that determine what kind of data it contains. Size and Type are examples.


filter <DAO definition>

filter

A set of criteria applied to records in order to create a subset of the records.


Float data type <DAO definition>

Float data type

A data type that stores a signed, approximate numeric value with mantissa precision 15 (zero or absolute value 10308 to 10308).


foreign key <DAO definition>

foreign key

One or more table fields that refer to the primary key field or fields in another table. A foreign key indicates how the tables are related — the data in the foreign key and primary key fields must match. For example, a list of valid part numbers would contain a foreign key to an inventory table containing references to valid part numbers. Used when establishing referential integrity for a database.


foreign table <DAO definition>

foreign table

A table that provides a foreign key to another table in the database. Generally, you use a foreign table to establish or enforce referential integrity. The foreign table is usually on the "many" side of a one-to-many relationship. An example of a foreign table is a table of customer orders.


form <DAO definition>

form

A window or dialog box. Forms are containers for controls. A multiple-document interface (MDI) form can also act as a container for child forms and some controls.


forward-only cursor <DAO definition>

forward-only cursor

A result set where the current position can only move forward by a specified number of records, or to the very last record. The current position cannot be moved back to the beginning of the result set or to previous records. The cursor membership, order, and values are generally fixed when the cursor is opened. If other users update, delete, or insert rows, the cursor doesn't reflect these changes until you close and reopen it.


forward-only-type Recordset <DAO definition>

forward-only–type Recordset

A Recordset object in which records can be searched only from beginning to end; the current record position cannot be moved back to the first record. Forward-only–type recordsets reduce processing overhead on remote databases. For example, you can use a forward-only–type Recordset on a linked remote table to quickly process data in one pass, such as when you’re building a customized report.


forward scroll <DAO definition>

forward scroll

Move toward the end (EOF) of a Recordset object.


FTP <DAO definition>

FTP

File Transfer Protocol. A protocol that makes it possible for a user to transfer files from one location to another over the Internet. URLs of files on FTP servers begin with ftp://.


Function procedure <DAO definition>

Function procedure

A procedure that performs a specific task within a Microsoft Visual Basic program and returns a value. A Function procedure begins with a Function statement and ends with an End Function statement.


globally unique identifier (GUID) <DAO definition>

globally unique identifier (GUID)

A 16-byte field used to establish a unique identifier for replication. GUIDs are used extensively to identify replicas, replica sets, tables, records, and other objects.

Note In Microsoft Access, GUIDs are referred to as Replication IDs.


group <DAO definition>

group

A collection of user accounts in a Workgroup object, identified by group name and personal identifier (PID). Permissions assigned to a group apply to all users in the group.


GUID data type <DAO definition>

GUID data type

Globally Unique Identifier/Universally Unique Identifier. A unique identification string used with remote procedure calls. Every interface and object class uses a GUID for identification. A GUID is a 128-bit value. For example, 12345678-1234-1234-1234-123456789ABC is a syntactically correct GUID. The GUIDs on the client and server must match for the client and server to bind. Vendors of objects can request that Microsoft allocate one or more sets of 256 GUIDs for their exclusive use. Alternatively, if you have a network card, you can run a tool named Uuidgen.exe, which provides a set of 256 GUIDs based on the time of day, the date, and a unique number contained in your network card.


HTTP <DAO definition>

HTTP

Hypertext Transfer Protocol. The behind-the-scenes Internet protocol that delivers information by way of the World Wide Web. The protocol makes it possible for a user to use a client program to enter a URL (or click a hyperlink) and retrieve text, graphics, sound, and other digital information from a Web server. URLs of files on Web servers begin with http://.


hub server <DAO definition>

hub server

A computer used in a star topology. A replica residing on this computer can be used as a synchronization partner with other replicas. See also base computer, satellite computer, or star topology.


hyperlink data type <DAO definition>

hyperlink data type

A field data type you use for fields that will store hyperlinks. Hyperlink fields contain text or combinations of text and numbers stored as text that are used as a hyperlink address. A hyperlink address can have up to three parts. Each part can contain up to 2048 characters and uses the syntax:

displaytext#address#subaddress


inconsistent <DAO definition>

inconsistent

The state of a multiple-table Recordset object that enables you to update all fields (columns). For example, in a Recordset created by joining two tables in a one-to-many join (as in a Customers and Orders table), you can update Orders.CustomerID so that it doesn’t match Customers.CustomerID, unless referential integrity disables the update.


index <DAO definition>

index

A dynamic cross-reference of one or more table data fields (columns) that permits faster retrieval of specific records from a table. As records are added, changed, or deleted, the database management system automatically updates the index to reflect the changes.

When used with a table-type Recordset object, the current index determines the order in which data records are returned to the Recordset. A table may have several indexes defined for its data.

A DAO Index object represents an index for a TableDef object.


indirect synchronization <DAO definition>

indirect synchronization

A type of synchronization that occurs when one Synchronizer leaves changes in a dropbox folder for another Synchronizer to pick up and apply to the replica it manages.


inner join <DAO definition>

inner join

A join in which records from two tables are combined and added to a Recordset only if the values of the joined fields meet a specified condition. For instance, an equi-join is an inner join in which the values of the joined fields must be equal.


installable ISAM <DAO definition>

installable ISAM

A driver you can specify that allows access to external database formats such as dBASE, Microsoft Excel, and Paradox. ISAM is an acronym for Indexed Sequential Access Method. The Microsoft Jet database engine installs (loads) these ISAM drivers when referenced by your application. The location of these drivers is maintained in the Microsoft Windows Registry.


instance <DAO definition>

instance

Any one of a set of objects sharing the same class. For example, multiple instances of a Form class share the same code and are loaded with the same controls with which the Form class was designed. During run time, the individual properties of controls on each instance can be set to different values.


Integer data type <DAO definition>

Integer data type

A fundamental data type that holds integer numbers. An Integer variable is stored as a 16-bit (2-byte) number ranging in value from -32,768 to 32,767.


Internet <DAO definition>

Internet

A worldwide network of thousands of smaller computer networks and millions of commercial, educational, government, and personal computers. The Internet is like an electronic city with virtual libraries, storefronts, business offices, art galleries, and so on.


intranet <DAO definition>

intranet

A network within an organization that uses Internet technologies (such as the HTTP or FTP protocols). You can use an intranet to navigate between objects, documents, Web pages, and other destinations using hyperlinks.


intrinsic constant <DAO definition>

intrinsic constant

A constant provided by an application. For example, Data Access Objects (DAO) constants are listed in the DAO object library and can be viewed by using the Object Browser.


join <DAO definition>

join

A database operation that combines some or all records from two or more tables, such as an equi-join, outer join, or self-join. Generally, a join refers to an association between a field in one table and a field of the same data type in another table. You create a join with an SQL statement.

When you define a relationship between two tables, you create a join by specifying the primary and foreign table fields. When you add a table to a query, you need to create a join between appropriate fields in the SQL statement that defines the query.


keyset cursor <DAO definition>

keyset cursor

A set of rows that you can use to add, change, or delete rows from an underlying database table or tables. Movement within the keyset is unrestricted. A keyset cursor can contain columns from one or more tables in a database. Membership is fixed.


left join <DAO definition>

left join

A left outer join includes all of the records from the first (left) of two tables, even if there are no matching values for records in the second (right) table.


left outer join <DAO definition>

left outer join

An outer join in which all the records from the left side of the LEFT JOIN operation in the query's SQL statement are added to the Recordset object, even if there are no matching values in the joined field from the table on the right. Records from the table on the right are combined with those from the table on the left only when there are matching values in the joined fields. When a left-side record has no match, a row of Null values is joined on the right side.


linked table <DAO definition>

linked table

A table in another database linked to a Microsoft Jet database. Data for linked tables remains in the external database where it can be manipulated by other applications. (Formerly known as attached tables.)


local object <DAO definition>

local object

A table, query, form, report, macro, or module that remains in the replica where it was created. Neither the object nor changes to the object are dispersed to other members in the replica set.


locked <DAO definition>

locked

The condition of a data page, Recordset object, or Database object that makes it read-only to all users except the one who is currently entering data in it.


Long Binary data type <DAO definition>

Long Binary data type

A type of field that can hold 1.2 GB of data. Long Binary fields can contain any type of binary data. (Also known as an OLE Object data type in Microsoft Access).


Long data type <DAO definition>

Long data type

A fundamental data type that holds long-integer numbers. A Long variable is stored as a 32-bit (4-byte) number ranging in value from -2,147,483,648 to 2,147,483,647.


make table query <DAO definition>

make table query

An action query that creates a new table from the Recordset object of an existing query.


managed replicas <DAO definition>

managed replicas

A replica with an assigned Synchronizer. The Synchronizer delivers changes to and receives changes from other replicas in the set.

Note If you don't assign a Synchronizer to a replica, you can still synchronize it in your application's code or by using another Synchronizer. However, you can't set synchronization schedules from this replica unless you assign a Synchronizer to the replica.


many-only table <DAO definition>

many-only table

A table that doesn’t appear as the "one" side of any join in a query.


Memo data type <DAO definition>

Memo data type

A field data type. Such fields can contain up to 1.2 GB of text data.


message <DAO definition>

message

A packet of information passed from one application to another.


method <DAO definition>

method

A procedure similar to a function that operates on specific objects.


Microsoft Jet-connected ODBC data source <DAO definition>

Microsoft Jet-connected ODBC data source

An ODBC data source that is accessed by using Data Access Objects (DAO) and the Microsoft Jet database engine.


Microsoft Jet database <DAO definition>

Microsoft Jet database

A database created with the Microsoft Jet database engine. The file name extension for a Microsoft Jet database is .mdb.


Microsoft Jet database engine <DAO definition>

Microsoft Jet database engine

A database management system that retrieves data from and stores data in user and system databases. The Microsoft Jet database engine can be thought of as a data manager component with which other data access systems, such as Microsoft Access and Microsoft Visual Basic, are built.


Microsoft Jet workspace <DAO definition>

Microsoft Jet workspace

A workspace that uses the Microsoft Jet database engine to access a data source. The data source can be a Microsoft Jet database file (.mdb), an ODBC database, such as a Paradox database, or an ISAM database.


Microsoft Replication Manager <DAO definition>

Microsoft Replication Manager

An application that provides a graphical user interface to manage the location, synchronization schedule, and relationship of one or more replicas with the other replicas in the set. Replication Manager manages the Synchronizer settings that govern replication, while the Synchronizer performs the actual synchronization activities. Replication Manager is part of the Microsoft Office 97, Developer Edition.


multiuser database <DAO definition>

multiuser database

A database that permits more than one user to access and modify the same set of data at the same time. In some cases, the additional "user" may be another instance of your application or another application running on your system that accesses the same data as some other application.


Numeric data type <DAO definition>

Numeric data type

A data type that stores a signed, exact numeric value with precision p and scale s (1 ≤ p ≤15; 0 ≤ s ≤ p).


normalize <DAO definition>

normalize

To minimize the duplication of information in a relational database through effective table design.


Null <DAO definition>

Null

A value that indicates missing or unknown data. Null values can be entered in fields for which information is unknown and in expressions and queries. In Microsoft Visual Basic, the Null keyword indicates a Null value. Some fields, such as those defined as containing the primary key, can’t contain Null values.


null field <DAO definition>

null field

A field containing no characters or values. A null field isn't the same as a zero-length string ("") or a field with a value of 0. A field is set to null when the content of the field is unknown. For example, a Date Completed field in a task table would be left null until a task is completed.


numeric expression <DAO definition>

numeric expression

Any expression that results in a number. This can be any combination of variables, constants, functions, and operators that evaluates to a number.


Object Browser <DAO definition>

Object Browser

A dialog box you can use to examine the contents of an object library to get information about the objects provided.


object expression <DAO definition>

object expression

An expression that specifies a particular object. This expression can include any of the object's containers. For example, if your application has an Application object that contains a Document object that contains a Text object, the following are valid object expressions:

Application.Document.Text
Application.Text
Document.Text
Text


object library <DAO definition>

object library

A dynamic-link library (DLL) with one or more type library resources that typically has the extension .olb. You can use the Object Browser to examine the contents of an object library to get information about the objects provided.


object replication <DAO definition>

object replication

The process of reproducing an object (table, query, report, form, macro, or module) so that two or more copies of the same object are synchronized. Changes made to the design of the object at the Design Master are sent and applied to all replicas in the set.


object variable <DAO definition>

object variable

A variable that contains a reference to an object.


ODBC (Open Database Connectivity) <DAO definition>

ODBC (Open Database Connectivity)

A standard protocol that permits applications to connect to a variety of external database servers or files. ODBC drivers used by the Microsoft Jet database engine permit access to Microsoft SQL Server and several other external databases.

The ODBC application programming interface (API) may also be used to access ODBC drivers and the databases they connect to without using the Microsoft Jet database engine.


ODBC data source <DAO definition>

ODBC data source

A term used to refer to a database or database server used as a source of data. ODBC data sources are referred to by their Data Source Name (DSN). Data sources can be created by using the Windows Control Panel or the RegisterDatabase method.


ODBCDirect <DAO definition>

ODBCDirect

A technology that allows you to access ODBC data sources directly by using DAO features that bypass the Microsoft Jet database engine.


ODBCDirect data source <DAO definition>

ODBCDirect data source

A data source that is accessed by using the DAO ODBCDirect features, which bypass the Microsoft Jet database engine.


ODBCDirect workspace <DAO definition>

ODBCDirect workspace

A workspace that uses ODBCDirect to access an ODBC data source directly, bypassing the Microsoft Jet database engine.


ODBC driver <DAO definition>

ODBC driver

A dynamic-link library (DLL) used to connect a specific Open Database Connectivity data source with another (client) application.


ODBC Driver Manager<DAO definition>

ODBC Driver Manager

An application that manages connections between ODBC-enabled data sources and the drivers used to access them.


OLE <DAO definition>

OLE

Microsoft's object-based technology that enables you to create applications that contain components from various other applications.


OLE Object data type <DAO definition>

OLE Object data type

A field data type you use for objects created in other applications that can be linked or embedded in a Microsoft Jet database. For example, you could use an OLE Object field to store a collection of pictures.


on-demand synchronization <DAO definition>

on-demand synchronization

The exchange of data between two replicas that occurs at the explicit request of the user.


one-to-many relationship <DAO definition>

one-to-many relationship

An association between two tables in which:

  • The primary key value of each record in the primary table corresponds to the value in the matching field or fields of many records in the related table.

    - or -

  • The primary key value of each record in the related table corresponds to the value in the matching field or fields of one and only one record in the primary table.


one-to-one relationship <DAO definition>

one-to-one relationship

An association between two tables in which:

  • The primary key value of each record in the primary table corresponds to the value in the matching field or fields of one and only one record in the related table.

    - or -

  • The primary key value of each record in the related table corresponds to the value in the matching field or fields of one and only one record in the primary table.


optimistic <DAO definition>

optimistic

A type of locking in which the data page containing one or more records, including the record being edited, is unavailable to other users only while the record is being updated by the Update method, but is available between the Edit and Update methods. Optimistic locking is used when accessing ODBC databases or when the LockEdits property of the Recordset object is set to False.


outer join <DAO definition>

outer join

A join in which all the records from one table are added to the Recordset object, even if there are no matching values in the joined field from the second table. Records from the second table are combined with those from the first table only when there are matching values in the joined fields. Null records are joined when there is no match.


page <DAO definition>

page

A portion of the database in which record data is stored. Depending on the size of the records, a page may contain more than one record. In Microsoft Jet databases (.mdb), a page is 2048 (2K) bytes in length.


parameter <DAO definition>

parameter

An element containing a value that you can change to affect the results of the query. For example, a query returning data about an employee might have a parameter for the employee's name. You can then use one QueryDef object to find data about any employee by setting the parameter to a specific name before running the query.


parameter query <DAO definition>

parameter query

A query that requires you to provide one or more criteria values, such as Redmond for City, before the query is run. A parameter query isn’t, strictly speaking, a separate kind of query; rather, it extends the flexibility of other queries.


parse <DAO definition>

parse

To identify the parts of a statement or expression and then validate those parts against the appropriate language rules.


partial replica <DAO definition>

partial replica

A database that contains only a subset of the records in a full replica. With a partial replica, you can set filters and identify relationships that define which subset of the records in the full replica should be present in the database.


pass-through query <DAO definition>

pass-through query

An SQL-specific query you use to send commands directly to an SQL database server (such as Microsoft SQL Server). With pass-through queries, you work with the tables on the server instead of linking them. Pass-through queries are used to execute SQL queries and system-specific commands written by using SQL dialects known only to the server.

A pass-through query may or may not return records. If it does, they are always returned in a snapshot.


permission <DAO definition>

permission

One or more attributes that specify what kind of access a user has to data or objects in a database. For example, if a user has read data permission for a table or query, the user can view or retrieve but not edit data in the table or query.


persistent object <DAO definition>

persistent object

An object stored in the database; for example, a database table or QueryDef object. Dynaset-type or snapshot-type Recordset objects are not considered persistent objects because they are created in memory as needed.


personal identifier (PID) <DAO definition>

personal identifier (PID)

A case-sensitive alphanumeric string 4-20 characters long that the Microsoft Jet database engine uses in combination with the account name to identify a user or group in a Workgroup object. You provide the PID and the account name when you create a new user or group.


pessimistic <DAO definition>

pessimistic

A type of locking in which the page containing one or more records, including the record being edited, is unavailable to other users when you use the Edit method, and remains unavailable until you use the Update method. Pessimistic locking is enabled when the LockEdits property of the Recordset object is set to True.


primary key <DAO definition>

primary key

One or more fields whose value or values uniquely identify each record in a table. In a relationship, a primary key is used to refer to specific records in one table from another table. A primary key is called a foreign key when it is referred to from another table. You can have only one primary key. An Employees table, for example, could use the social security number for the primary key.


primary table <DAO definition>

primary table

The "one" side of two related tables in a one-to-many relationship with a foreign table. Generally, a primary key table is used to establish or enforce referential integrity.


procedural query <DAO definition>

procedural query

An SQL statement that executes a stored procedure.


property <DAO definition>

property

A named attribute of an object. Properties define object characteristics such as size, color, and screen location, or the state of an object, such as enabled or disabled.


pseudo index <DAO definition>

pseudo index

A dynamic cross-reference of one or more table data fields (columns) that permits an ODBC table (server table) without a unique index to be edited. A pseudo index is not an actual index on the server table, but a cross-reference that the Microsoft Jet database engine can use to support table updates. A pseudo index is necessary only if an ODBC table doesn’t have a unique index, which allows the table to be updated, or if there is no need to update the table. (Tables cannot have a unique index if they were intended to be read-only.) In previous versions, pseudo indexes were called index specifications.


query <DAO definition>

query

A formalized instruction to a database to either return a set of records or perform a specified action on a set of records as specified in the query. For example, the following SQL query statement returns records:

SELECT CompanyName FROM Publishers WHERE Region = 'NY'

You can create and run select, action, crosstab, parameter, and SQL-specific queries.


read-only <DAO definition>

read-only

A type of access to data whereby information can be retrieved but not modified.


record <DAO definition>

record

A set of related data about a person, place, event, or some other item. Table data is stored in records (rows) in the database. Each record is composed of a set of related fields (columns) — each field defining one attribute of information for the record. Taken together, a record defines one specific unit of retrievable information in a database.


referential integrity <DAO definition>

referential integrity

Rules that you set to establish and preserve relationships between tables when you add, change, or delete records. Enforcing referential integrity prohibits users from adding records to a joined table for which there is no primary key, changing values in a primary table that would result in orphaned records in a joined table, and deleting records from a primary table when there are matching related records.

If you select the dbRelationDeleteCascade or dbRelationUpdateCascade option for a relationship, the Microsoft Jet database engine allows changes and deletions but changes or deletes related records to make sure the rules are still enforced.


relationship <DAO definition>

relationship

An association established between common fields (columns) in two tables. A relationship can be one-to-one, many-to-many, or one-to-many.


replica <DAO definition>

replica

A copy of a database, including its tables, queries, forms, reports, macros, and modules. A replica is a member of a replica set and can be synchronized with other replicas in the set. Changes to the data in a replicated table in one replica are sent and applied to the other members in the replica set.

Note The Design Master is also a replica.


replica set <DAO definition>

replica set

Replicas that share the same database design and unique replica set identifier. Synchronization occurs between replica set members.


replica set member <DAO definition>

replica set member

A replica that belongs to a replica set. Members of a replica set share the same database design and can be synchronized with one another.


replica set topology <DAO definition>

replica set topology

The order in which changes are propagated from replica to replica. Topology is important because it determines how quickly changes in another replica appear in your replica.


replicated database <DAO definition>

replicated database

A database to which additional tables, fields, and properties have been added to record information about changes to data and the design of replicated objects in the database.


replicate <DAO definition>

replicate

To produce a replica, or copy, of something — for example, a database.


replicated object <DAO definition>

replicated object

A table, query, form, report, macro, or module that is in all replicas in the replica set. You can change the replicated object only at the Design Master, and these changes are dispersed to other replicas in the replica set during a synchronization.


replication <DAO definition>

replication

The process of creating and synchronizing replicas in separate locations. Replication adds system fields, system tables, and replication properties to a database so that changes made to the data in or to the design of a database are sent and applied to all the members of the replica set.


requery <DAO definition>

requery

To rerun a query to reflect changes to the records, retrieve newly added records, and eliminate deleted records.


reserved word <DAO definition>

reserved word

A word that is part of a language, such as the Microsoft Jet database engine SQL language. Reserved words include the names of statements, predefined functions and data types, methods, operators, and objects. Examples include SELECT, UPDATE, BETWEEN, SET, and INSERT. Don’t use reserved words for variable or object names.


right join <DAO definition>

right join

A right outer join includes all of the records from the second (right) of two tables, even if there are no matching values for records in the first (left) table.

For example, you could use LEFT JOIN with the Departments (left) and Employees (right) tables to select all departments, including those that have no employees assigned to them. To select all employees, including those who aren't assigned to a department, you would use RIGHT JOIN.


right outer join <DAO definition>

right outer join

An outer join in which all the records from the right side of the RIGHT JOIN operation in the query's SQL statement are added to the Recordset object, even if there are no matching values in the joined field from the left table. Records from the left table are combined with those from the right table only when there are matching values in the joined fields.


row <DAO definition>

row

A set of related columns or fields used to hold data. A row is synonymous with a record in the Microsoft Jet database engine. A table is composed of zero or more rows of data.


run time <DAO definition>

run time

The time when code is running. During run time, you interact with the code as a user would.


run-time error <DAO definition>

run-time error

An error that occurs when code is running. A run-time error results when a statement attempts an invalid operation.


retention period <DAO definition>

retention period

The number of days the system will retain certain replication system information for a replica. If the retention period expires before a replica is synchronized, the synchronization will fail.


satellite computer <DAO definition>

satellite computer

In a star topology, a computer on which a replica resides. This replica is copied from the base computer and synchronizes with a replica on the hub server by default. See also base computer, hub server, star topology.


schedule <DAO definition>

schedule

The times when the Synchronizer will initiate synchronization with other replicas. The minimum increment of time between scheduled synchronizations is 15 minutes. You can set different schedules between any two Synchronizers.


scheduled synchronization <DAO definition>

scheduled synchronization

An exchange of data between two replicas that occurs at a predetermined time.


scope <DAO definition>

scope

The attribute of a variable or procedure that determines which sections of which modules recognize it. There are three levels of scope: public, module, and procedure. Variables that you declare with Public can be accessed by any module, while variables that you declare in a specific module can be used only within that module. Also, variables that you declare in a Sub or Function procedure can be used only in that particular procedure.


secure workgroup <DAO definition>

secure workgroup

A Microsoft Jet database Workgroup object to which users log on with a user name and password and in which access to database objects is restricted according to permissions specified for user accounts and groups.


security <DAO definition>

security

A set of features used to specify or restrict the access that specified users or user groups have to data and objects in a database.


select query <DAO definition>

select query

A query that asks a question about the data stored in your tables and returns a Recordset object without changing the data. Once the Recordset data is retrieved, you can examine and make changes to the data in the underlying tables. In contrast, action queries can make changes to your data, but they don't return data records.


self-join <DAO definition>

self-join

A join in which records from a table are combined with other records from the same table when there are matching values in the joined fields. A self-join can be an inner join or an outer join. A self-join is useful when you ask hierarchical questions, such as a query that shows all the managers and the people who report to them.


server <DAO definition>

server

The database management system designed to share data with client applications; servers and clients are often connected over a network. A database server usually contains and manages a central repository of data that remote client applications can retrieve and manipulate.


server-side cursor <DAO definition>

server-side cursor

Cursors that reside on the server, as opposed to residing on the client computer. While client-side cursors copy the cursor to the workstation, server-side cursors use the resources of the database server to maintain the cursors.


session <DAO definition>

session

A session delineates a sequence of operations performed by the Microsoft Jet database engine. A session begins when a user logs on and ends when a user logs off. All operations performed during a session form one transaction scope and are subject to permissions determined by the logon user name and password. Sessions are implemented as Workspace objects by DAO.


shared network folder <DAO definition>

shared network folder

See dropbox folder.


Short data type <DAO definition>

Short data type

A Microsoft Jet database engine fundamental data type that corresponds to the Integer data type defined by Microsoft Visual Basic for Applications. A Short variable is stored as a 16-bit (2-byte) number ranging in value from -32,768 to 32,767.


Single data type <DAO definition>

Single data type

A fundamental data type that holds single-precision floating-point numbers in IEEE format. A Single variable is stored as a 32-bit (4-byte) number ranging in value from -3.402823E38 to -1.401298E-45 for negative values, from 1.401298E-45 to 3.402823E38 for positive values, and 0.


snapshot <DAO definition>

snapshot

A fixed copy of a set of records retrieved from the database and copied into memory. A snapshot derived from a Microsoft Jet-connected data source can’t be updated. Snapshot-type Recordset objects can be created from a base table, a query, or another Recordset. All SQL pass-through queries return snapshots.


sort order <DAO definition>

sort order

A sequencing principle used to order data, alphabetically or numerically. The sort order can be either ascending or descending.


SQL-specific query <DAO definition>

SQL-specific query

A query that can be created only by writing an SQL statement. Subqueries and pass-through, union, and data-definition queries are SQL-specific queries.


SQL statement/string <DAO definition>

SQL statement/string

An expression that defines a Structured Query Language (SQL) command, such as SELECT, UPDATE, or DELETE, and may include clauses such as WHERE and ORDER BY. SQL strings and statements are typically used in queries, Recordset objects, and aggregate functions, but can also be used to create or modify a database structure.


standard deviation <DAO definition>

standard deviation

A parameter that indicates the way in which a probability function is centered around its mean and that is equal to the square root of the moment in which the deviation from the mean is squared. Used to describe sets of values to determine how far the value varies from the arithmetic mean or average.


standard naming conventions <DAO definition>

standard naming conventions

A set of specific rules for naming DAO objects. Names can be up to 64 characters long and can include any combination of letters, numbers, spaces, and special characters except a period (.), an exclamation point (!), a backquote character (`), and brackets ([ ]). You also can't use leading spaces or control characters (ASCII values 0 through 31).


star topology <DAO definition>

star topology

A type of organizational map for networked computers. For replication, it refers to a hub server, base computer, and the distribution of members of the replica set on other satellite computers. Topology is important for determining synchronization schedules. See also base computer, hub server, satellite computer.


static cursor <DAO definition>

static cursor

A result set where the membership, order, and values are generally fixed when the cursor is opened. If other users update, delete, or insert rows, the cursor doesn't reflect these changes until you close and reopen it.


string comparison <DAO definition>

string comparison

The use of an operator to determine whether one string is greater than or equal to another string. If you use Option Compare Text in the Declarations section of a module, string comparisons are not case-sensitive. If you use Option Compare Binary, comparisons are case-sensitive. If you use Option Compare Database, the comparison method is set by the current database.


String data type <DAO definition>

String data type

A fundamental data type that holds character information. A String variable is either fixed-length or variable-length and contains one character per byte. Fixed-length strings are declared to be a specific length and can contain 1 to approximately 64K (2^16) characters. Variable-length strings can be any length up to 2 billion (2^31) characters (approximately 64K [2^16] characters for Microsoft Windows version 3.1 and earlier), less a small amount of storage overhead.


string expression <DAO definition>

string expression

Any expression that evaluates to a sequence of contiguous characters. Elements of the expression can include a function that returns a string, a string literal, a string constant, a string variable, a string Variant, or a function that returns a string Variant (VarType 8).


Structured Query Language (SQL) <DAO definition>

Structured Query Language (SQL)

A language used in querying, updating, and managing relational databases. SQL can be used to retrieve, sort, and filter specific data to be extracted from the database.

You can use SQL SELECT statements anywhere a table name, query name, or field name is accepted. For example, you can use an SQL statement in place of a table name in the OpenRecordset method.


subquery <DAO definition>

subquery

A subquery is a SELECT statement nested inside a SELECT, SELECT...INTO, INSERT...INTO, DELETE, or UPDATE statement or inside another subquery.


synchronization <DAO definition>

synchronization

The process of updating two replicas in which all updated records and objects are exchanged. The exchange of data between two replicas can be one-way or two-way and may be handled by a Synchronizer.


synchronization conflict <DAO definition>

synchronization conflict

A situation in which users of two replicas have changed the same record. One of the updated records is selected as the "winner," and the record in the "losing" replica is updated to contain this data. The other updated record is placed in a conflict table in the losing replica.


synchronization error <DAO definition>

synchronization error

A problem that occurs during synchronization that prevents changes to a record from being completed successfully. This is more serious than a conflict and should be resolved as soon as possible.


Synchronization window <DAO definition>

Synchronization window

The area of the Replication Manager where Synchronizers appear. You can move the Synchronizers, and zoom in or zoom out to see more or fewer Synchronizers. You can also click the line between two Synchronizers to edit their synchronization schedule. To understand the different icons in the Synchronization window, click Legend on the View menu.


Synchronizer <DAO definition>

Synchronizer

A program that monitors changes to a replica and handles the actual exchange of data between replicas. The Synchronizer operates in the background and appears in the taskbar. You can see the Synchronizers for a replica set in the Synchronization window in Replication Manager.

Note The previous version of Replication Manager referred to Synchronizers as Transporters.


syntax error <DAO definition>

syntax error

An error that occurs when you enter a line of code that Microsoft Visual Basic doesn't recognize.

Note Syntax rules for individual keywords are defined in the Syntax section of the associated Help topic. To get Help on a keyword from within the development environment, select the keyword and press F1.


system object <DAO definition>

system object

A database object defined by the Microsoft Jet database engine, such as the table MSysIndexes.


table <DAO definition>

table

The basic unit of data storage in a relational database. A table stores data in records (rows) and fields (columns) and is usually about a particular category of things, such as employees or parts. Also called a base table.

A table-type Recordset is a logical representation of a base table in a database.


TEMP <DAO definition>

TEMP

A TEMP environment variable is set by your autoexec.bat file when you start your system. Generally, TEMP points to an area on your hard disk used by Microsoft Windows and other programs, like the Microsoft Jet database engine, to store information that doesn't need to be saved after you shut down your system. For example, the following line in your autoexec.bat file points the TEMP environment variable to the D:\TempArea folder:

SET TEMP=D:\TempArea


temporary disk <DAO definition>

temporary disk

The disk or directory, identified by the TEMP operating system environment variable, where the Microsoft Jet database engine stores temporary files and result sets. Also known as a temporary drive. Although the TEMP environment variable can point to a RAM disk, this isn’t recommended.


Text data type <DAO definition>

Text data type

A field data type. Text fields can contain up to 255 characters or the number of characters specified by the Size property of the Field object, whichever is less. If the Size property of the text field is set to 0, the text field can hold up to 255 characters of data.


Time data type <DAO definition>

Time data type

A data type that stores a time value. The value is dependent on the clock setting of the data source.


TimeStamp data type <DAO definition>

TimeStamp data type

A data type that stores a TimeStamp. The value is dependent on the clock setting of the data source.


transaction <DAO definition>

transaction

A series of changes made to a database's data and schema. Mark the beginning of a transaction with the BeginTrans statement, commit the transaction by using the CommitTrans statement, and undo all your changes since BeginTrans by using the Rollback statement.

Transactions are optional and can be nested up to five levels. Transactions increase the speed of operations that change data and enable you to reverse changes easily.

Transactions are global to the referenced database object's Workspace.


union query <DAO definition>

union query

An SQL-specific select query that creates a snapshot-type Recordset object containing data from all specified records in two or more tables with any duplicate records removed. To include the duplicates, add the keyword ALL.

For instance, a union query of the Customers table and the Suppliers table results in a snapshot-type Recordset that contains all suppliers that are also customers.


unmanaged replica <DAO definition>

unmanaged replica

A replica that is not managed by a Synchronizer. Unmanaged replicas appear on the Synchronization window with a special icon. You cannot set synchronization schedules from an unmanaged replica, although they can be synchronized by another Synchronizer or through DAO code.


update <DAO definition>

update

The process that saves changes to data in a record. Until the record is saved, changes are stored in a temporary record called the copy buffer. The UPDATE clause in an SQL statement changes data values in one or more records (rows) in a database table.


update query <DAO definition>

update query

An action query that changes a set of records according to criteria you specify. An update query doesn’t return any records.


user account <DAO definition>

user account

An account identified by a user name and personal identifier (PID) that is created to manage access to database objects in a Microsoft Jet database Workgroup object.


validation <DAO definition>

validation

The process of checking whether entered data meets certain conditions or limitations.


validation properties <DAO definition>

validation properties

Properties used to set conditions on table fields and records. Validation properties include ValidationRule, Required, and AllowZeroLength.


validation rule <DAO definition>

validation rule

A rule that sets limits or conditions on what can be entered in one or more fields. Validation rules can be set for a Field or TableDef object. Validation rules are checked when you update a record containing fields requiring validation. If the rule is violated, a trappable error results.


VarBinary data type <DAO definition>

VarBinary data type

A data type that stores variable-length binary data. The maximum length is 255 bytes.


variable <DAO definition>

variable

A named storage location that can contain data that can be modified during program execution. Each variable has a name that uniquely identifies it within its level of scope. A data type can be specified or not.

Variable names:

  • Must begin with an alphabetic character.

  • Can't contain an embedded period or type-declaration character.

  • Must be unique within the same scope.

  • Must be no longer than 255 characters.


variance <DAO definition>

variance

The square of the standard deviation. It is a measure of the amount by which all values in a group vary from the average value of the group.


Variant data type <DAO definition>

Variant data type

A special data type that can contain numeric, string, or date data as well as the special values Empty and Null. The VarType function defines how the data in a Variant is treated. All variables become variant types if not explicitly declared as some other type.


variant expression <DAO definition>

variant expression

Any expression that can evaluate to numeric, string, or date data as well as the special values Empty and Null.


wildcard characters <DAO definition>

wildcard characters

The asterisk (*), question mark (?), number sign (#), exclamation point (!), hyphen (-), and brackets ([ ]) are wildcard characters. You can use these characters in queries and expressions to include all records, file names, or other items that begin with specific characters or match a certain pattern. You can also use wildcard characters and matching characters to further refine a search when using an SQL statement.

Symbol | Usage | Example
* | Matches any number of characters, and can be used anywhere in the character string | wh* finds what, white, and why *at finds cat, bat, and what
? | Matches any single character | b?ll finds ball, bell, and bill
# | Matches any single digit | 1#3 finds 103, 113, 123
[ ] | Matches any single character within the brackets | b[ae]ll finds ball and bell but not bill
! | Matches any character not in the list | b[!ae]ll finds bill and bull but not bell or ball
- | Matches any one of a range of characters | b[a-c]d finds bad, bbd, and bcd

Note The wildcard characters * (asterisk), ? (question mark), # (number sign), and [ (opening bracket) can match themselves only if enclosed in brackets.


workgroup <DAO definition>

workgroup

A group of users in a multiuser environment who share data and the same workgroup information file (typically the System.mdw file).


workgroup administrator <DAO definition>

workgroup administrator

A member of the group Admins in a Microsoft Jet database Workgroup object. A workgroup administrator can always obtain full permissions for any database object created in the Workgroup.


zero-length string <DAO definition>

zero-length string

A string containing no characters (""). The Len function of a zero-length string returns 0.


expression <DAO definition>

expression

Any combination of operators, constants, literal values, functions, and names of fields, controls, and properties that evaluates to a single value. You can use expressions as settings for many properties and action arguments, to set criteria, or define calculated fields in queries.


alias <DAO definition>

alias

Visual Basic: An alternate name you give to an external procedure to avoid conflict with a Visual Basic keyword, public variable, constant, or a name not allowed by the Visual Basic naming conventions.

Structured Query Language (SQL): An alternate name you give to a field or expression in a SELECT statement (using the AS clause).


consistent <DAO definition>

consistent

The state of a multiple-table Recordset object that allows you to perform only updates that result in a consistent view of the data. For example, in a Recordset that is a join of two or more tables (a one-to-many relationship), a consistent query would not allow you to set the many-side key to a value that isn’t in the one-side table.


external database <DAO definition>

external database

Either an ODBC database such as Microsoft SQL Server that resides on a remote server, or one of the external databases such as Paradox, dBASE, FoxPro, Microsoft Excel, Microsoft Access, Lotus 1-2-3, HTML, and Text.


dates and times <DAO definition>

dates and times

Dates and times are stored internally as different parts of a real number.

The value to the left of the decimal represents a date between December 30, 1899 and December 30, 9999, inclusive. Negative values represent dates prior to December 30, 1899.

The value to the right of the decimal represents a time between 0:00:00 and 23:59:59, inclusive. Midday is represented by .5.


make-table query <DAO definition>

make-table query

An action query that creates a new table from the Recordset object of an existing query.


ASCII Character Set <DAO definition>

ASCII Character Set

American Standard Code for Information Interchange (ASCII) 7-bit character set widely used to represent letters and symbols found on a standard U.S. keyboard. The ASCII character set is the same as the first 128 characters (0 ? 127) in the ANSI character set.


Function procedure <DAO definition>

Function procedure

A procedure that performs a specific task within a Visual Basic program and returns a value. A Function procedure begins with a Function statement and ends with an End Function statement.


ANSI Character Set <DAO definition>

ANSI Character Set

An 8-bit character set used by Microsoft Windows that allows you to represent up to 256 characters (0 through 255) using your keyboard. The ASCII character set is a subset of the ANSI set.


crosstab query <DAO definition>

crosstab query

A query that calculates a sum, average, count, or other type of total on records, and then groups the result by two types of information ? one down the left side of a grid (row headings) and the other across the top (column headings). For example, the Quarterly Orders by Product query in the Northwind sample database is a crosstab query.


Byte data type <DAO definition>

Byte data type

A fundamental data type used to hold small positive integer numbers ranging from 0 to 255.


field <DAO definition>

field

A category of information stored in a table in a database ? a column of data. An element of a database table that contains a specific item of information, such as last name.


Microsoft Jet database engine <DAO definition>

Microsoft Jet database engine

A database management system that retrieves data from and stores data in user and system databases. The Microsoft Jet database engine can be thought of as a data manager component with which other data access systems, such as Microsoft Access and Visual Basic, are built.


column <DAO definition>

column

The visual representation of a field in a grid. A column defines the data type, size, and other attributes of one field of a row (record) of data. All columns taken as a set define a row (record) in the database. An individual column contains data related in type and purpose throughout the table; that is, a column's definition doesn’t change from row to row.


forward-only-type Recordset <DAO definition>

forward-only – type Recordset

A Recordset object in which records can be searched only from beginning to end; the current record position can't be moved back to the first record. Forward-only – type recordsets reduce processing overhead on remote databases. For example, you can use a forward-only – type Recordset on a linked remote table to quickly process data in one pass, such as when you’re building a customized report.


autonumber field <DAO definition>

AutoNumber field

A field data type that automatically stores a unique number for each record as it's added to a table. An AutoNumber field always uses the Long data type, and numbers generated by an AutoNumber field can't be modified. (Also known as a Counter field.)


pass-through query <DAO definition>

pass-through query

An SQL-specific query you use to send commands directly to a SQL database server (such as Microsoft SQL Server). With pass-through queries, you work with the tables on the server instead of linking them. Pass-through queries are used to execute SQL queries and system-specific commands written by using SQL dialects known only to the server.

A pass-through query may or may not return records. If it does, they are always returned in a snapshot.


Null <DAO definition>

Null

A value that indicates missing or unknown data. Null values can be entered in fields for which information is unknown and in expressions and queries. In Visual Basic, the Null keyword indicates a Null value. Some fields, such as those defined as containing the primary key, can’t contain Null values.


syntax error <DAO definition>

syntax error

An error that occurs when you enter a line of code that Visual Basic doesn't recognize.

Note Syntax rules for individual keywords are defined in the Syntax section of the associated Help topic. To get Help on a keyword from within the development environment, select the keyword and press F1.


wildcard characters <DAO definition>

wildcard characters

The asterisk (*), question mark (?), number sign (#), exclamation point (!), hyphen (-), and brackets ([ ]) are wildcard characters. You can use these characters in queries and expressions to include all records, file names, or other items that begin with specific characters or match a certain pattern. You can also use wildcard characters and matching characters to further refine a search when using an SQL statement.

Symbol | Example |  | Usage
* | wh* finds what, white, and why *at finds cat, bat, and what |  | Matches any number of characters, and can be used anywhere in the character string.
? | b?ll finds ball, bell, and bill |  | Matches any single character.
# | 1#3 finds 103, 113, 123 |  | Matches any single digit.
[ ] | b[ae]ll finds ball and bell but not bill |  | Matches any single character within the brackets.
! | b[!ae]ll finds bill and bull but not bell or ball |  | Matches any character not in the list.
- | b[a-c]d finds bad, bbd, and bcd | Matches any one of a range of characters.

Note The wildcard characters * (asterisk), ? (question mark), # (number sign), and [ (opening bracket) can match themselves only if enclosed in brackets.


SQL statement/string <DAO definition>

SQL statement/string

An expression that defines a Structured Query Language (SQL) command, such as SELECT, UPDATE, or DELETE, and may include clauses such as WHERE and ORDER BY. SQL strings and statements are typically used in queries, Recordset objects, and aggregate functions but can also be used to create or modify a database structure.


record <DAO definition>

record

A set of related data about a person, place, event, or some other item. Table data is stored in records (rows) in the database. Each record is composed of a set of related fields (columns) ? each field defining one attribute of information for the record. Taken together, a record defines one specific unit of retrievable information in a database.


one-to-one relationship <DAO definition>

one-to-one relationship

An association between two tables in which:

  • The primary key value of each record in the primary table corresponds to the value in the matching field or fields of one and only one record in the related table.

  • The primary key value of each record in the related table corresponds to the value in the matching field or fields of one and only one record in the primary table.


one-to-many relationship <DAO definition>

one-to-many relationship

An association between two tables in which:

  • The primary key value of each record in the primary table corresponds to the value in the matching field or fields of many records in the related table.

  • The primary key value of each record in the related table corresponds to the value in the matching field or fields of one and only one record in the primary table.


pseudo index <DAO definition>

pseudo index

A dynamic cross-reference of one or more table data fields (columns) that permits an ODBC table (server table) without a unique index to be edited. A pseudo index is not an actual index on the server table, but a cross-reference that the Microsoft Jet database engine can use to support table updates. A pseudo index is necessary only if an ODBC table doesn’t have a unique index, which allows the table to be updated. You don’t need a pseudo index if the table already has a unique index or if there is no need to update the table. (Tables cannot have a unique index if they were intended to be read-only.) In previous versions, pseudo indexes were called index specifications.


Short data type <DAO definition>

Short data type

A Microsoft Jet database engine fundamental data type that corresponds to the Integer data type defined by Visual Basic for Applications. A Short variable is stored as a 16-bit (2-byte) number ranging in value from -32,768 to 32,767.


Comparison of Data Types

The Microsoft Jet database engine recognizes several overlapping sets of data types; which data type you use depends on whether or not you're writing code in Visual Basic or in one of the Microsoft Access development contexts. In Microsoft Access, there are four different contexts, each with its own set of data types ? a table's Design view, the Query Parameters dialog box, Access Basic, and a query's SQL view. See online Help in Microsoft Access for more information on these contexts.

The following table compares the four sets of data types that correspond to each context. The first column lists the Type property settings available in a table's Design view and the five FieldSize property settings for the Number data type. The second column lists the data types for designing parameter queries that are available in the Query Parameters dialog box. The third column lists the Visual Basic data types. The fourth column lists the Microsoft Access SQL data types defined by the Jet engine along with their valid synonyms.

Table fields | Query parameters | Visual Basic | Microsoft Access SQL and synonyms
Not supported | Binary | Not supported | BINARY (See Notes) VARBINARY
Yes/No | Yes/No | Boolean | BOOLEAN BIT, LOGICAL, LOGICAL1, YESNO
Number; Size = Byte | Byte | Byte | BYTE INTEGER1
Counter | Not supported | Long | COUNTER AUTOINCREMENT
Currency | Currency | Currency | CURRENCY MONEY
Date/Time | Date/Time | Variant (See Notes) | DATETIME DATE, TIME, TIMESTAMP
Number or AutoNumber; Size = ReplicaID | Not supported | Not supported | GUID
Number; Size = Single | Single | Single | SINGLE, FLOAT4, IEEESINGLE, REAL
Number; Size = Double | Double | Double | DOUBLE FLOAT, FLOAT8, IEEEDOUBLE, NUMBER, NUMERIC
Number; Size = Integer | Integer (See Notes) | Integer (See Notes) | SHORT, INTEGER2, SMALLINT
Number; Size = Long Integer | Long Integer | Long | LONG (See Notes) INT, INTEGER, INTEGER4
OLE Object | OLE Object | String | LONGBINARY GENERAL, OLEOBJECT
Memo | Memo | String | LONGTEXT LONGCHAR, MEMO, NOTE
Text | Text | String | TEXT ALPHANUMERIC, CHAR, CHARACTER, STRING, VARCHAR
Not supported | Value | Variant | VALUE (See Notes)

Notes

  • If you want to declare a Visual Basic variable that contains date/time information, declare it as a Variant. If you create a Date/Time table field in SQL view or in a table's Design view using Microsoft Access, check the field's Type property in Visual Basic; the returned integer constant corresponds to the constant dbDate (defined by the Jet engine) instead of the Variant date constant vbDate. The variable types represented by these two constants are fully compatible, however, and no type mismatch error will occur if a Variant variable contains data from a Date/Time field in a Jet engine table or query.

  • The Integer data type in Jet engine SQL doesn't correspond to the Integer data type for table fields, query parameters, or Visual Basic. Instead, in Jet engine SQL, Integer corresponds to a Long Integer for table fields and query parameters and to a Long data type in Visual Basic.

  • The VALUE reserved word doesn't represent a data type defined by the Jet database engine. However, in Microsoft Access or SQL queries, VALUE can be considered a valid synonym for the Visual Basic Variant data type.


IniPath Property (dbDAO)

CdbDBEngine::SetIniPath, GetIniPath Property

Sets or returns information about the Windows registry key that contains values for the Microsoft Jet database engine (Microsoft Jet workspaces only).

Settings and Return Values

The setting or return value is a string that points to a user-supplied portion of the Windows registry key containing Microsoft Jet database engine settings or parameters needed for installable ISAM databases.

Syntax

VOIDSetIniPath(LPCTSTR pstr);

CStringGetIniPath(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | Pointer to a string containing the user-supplied portion of the registry key.


LoginTimeout Property (dbDAO)

CdbDBEngine::SetLoginTimeout, GetLoginTimeout Property

Sets or returns the number of seconds before an error occurs when you attempt to log in to an ODBC database.

Settings and Return Values

The setting or return value is an integer representing the number of seconds before a login timeout error occurs. The default LoginTimeout property setting is 20 seconds. When the LoginTimeout property is set to 0, no timeout occurs.

Syntax

VOIDSetLoginTimeout(SHORT s);

SHORTGetLoginTimeout(VOID);

Set Parameters

Type | Example | Description
SHORT | s | A short integer containing the number of seconds before a login timeout error occurs.


GetVersion Property (dbDAO)

CdbDBEngine::GetVersion Property

Returns a value that identifies the version number of DAO currently in use.

Syntax

CStringGetVersion(VOID);


OpenDatabase Method (dbDAO)

CdbDBEngine::OpenDatabase Method

Opens a specified database in a Workspace object and returns a reference to the Database object that represents it.

Syntax

CdbDatabaseOpenDatabase(LPCTSTR pstrName,

BOOL bExclusive=FALSE,

BOOL bReadOnly=FALSE,

LPCTSTR pstrConnect=NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName | A pointer to string that is the name of an existing Microsoft Jet database file, or the data source name (DSN) of an ODBC data source. See the Name property for more information about setting this value.
BOOL | bExclusive | A Boolean. For Microsoft Jet workspaces only: TRUEOpens the database in exclusive mode. FALSE(Default) opens the database in shared mode.
BOOL | bReadOnly | Optional. A Boolean. TRUEOpens the database with read-only access. FALSE(Default) Opens the database with read/write access.
LPCTSTR | pstrConnect | Optional. A pointer to a string composed of a database type specifier and zero or more parameters separated by semicolons. This parameter passes additional information to ODBC and certain ISAM drivers as needed.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbDBEngine      dben;
CdbDatabase      db;
// Open a local Jet database in exclusive, read/write mode.
db = dben.OpenDatabase(_T("C:\\YourJetDB.mdb"), TRUE);


OpenConnection Method (dbDAO);

CdbDBEngine::OpenConnection Method

Opens a Connection object on an ODBC data source (ODBCDirect workspaces only).

Syntax

CdbConnectionOpenConnection(LPCTSTR pstrName,

LONG lOption=-1L,

BOOL bReadOnly=FALSE,

LPCTSTR pstrConnect=NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName | A pointer to a string that contains the name of a registered ODBC data source (DSN). If it doesn't refer to a valid ODBC data source name, an error occurs.
LONG | IOption | Optional. A Long value that specifies how the ODBC driver manager should prompt the user for connection information such as DSN, user name, and password. Possible values are described in Remarks.
BOOL | bReadOnly | Optional. A Boolean. TRUEOpens a Connection object for read-only access. FALSE(Default) Opens a Connection object for read/write access.
LPCTSTR | pstrConnect | Optional. A pointer to a string that contains the ODBC connect string. See the Connect property for the specific elements and syntax of this string. A prepended "ODBC;" is required. If Connect is omitted (default), the UID and/or PWD will be taken from the UserName and Password properties of the Workspace.

Remarks

The following are valid Options values.

Constant | Description
dbDriverNoPrompt | The ODBC driver manager uses the connection string provided in Name and Connect. If sufficient information is not provided, a trappable error is returned.
dbDriverPrompt | The driver manager displays the ODBC Data Sources dialog box. The connection string used to establish the connection is constructed from the DSN selected and completed by the user via the dialog boxes, or, if no DSN is chosen, the default DSN is used.
dbDriverComplete | If the Connect argument includes the DSN keyword, the driver manager uses the string as provided in Connect. Otherwise it behaves as it does when dbDriverPrompt is specified.
dbDriverCompleteRequired | Behaves like dbDriverComplete except the driver disables the prompts for any information not required to complete the connection.

The OpenConnection method is similar but not equivalent to OpenDatabase. The main difference is that OpenConnection is available only in an ODBCDirect workspace.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbDBEngine      dben(..., dbUseODBC);
CdbConnection   conn;
CdbRecordset      rstX;
conn = dben.OpenConnection(_T("ODBC;..."), dbDriverNoPrompt,
                           FALSE, T("DATABASE=SomeDB..."));
rstX = conn.OpenRecordset(...);


CreateWorkspace Method (dbDAO)

CdbDBEngine::CreateWorkspace Method

Creates a new Workspace object.

Syntax

CdbWorkspaceCreateWorkspace(LPCTSTR pstrName,

LPCTSTR pstrUser,

LPCTSTR pstrPassword,

LONG lType=dbUseJet);

Parameters

Type | Example | Description
LPCTSTR | pstrName | A pointer to a string that uniquely names the new Workspace object. See the Name property for details on valid workspace names.
LPCTSTR | pstrUser | A pointer to a string that identifies the owner of the new Workspace object. See the UserName property for more information.
LPCTSTR | pstrPassword | A pointer to a string containing the password for the new Workspace object. The password can be up to 14 characters long and can include any characters except ASCII character 0 (null). See the Password property for more information on valid passwords.
LONG | IType | An integer that specifies whether the type of the workspace should be Microsoft Jet or ODBC. The default is a Microsoft Jet workspace.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbDBEngine      dben;
CdbWorkspace      ws;
ws = dben.CreateWorkspace(   _T("MyWorkSpace"), _T("IOwnIt"),                               _T("MyPassword"), dbUseJet);


SystemDB Property (dbDAO)

CdbDBEngine::SetSystemDB, GetSystemDB Property

Sets or returns the path for the current location of the system database file.

Settings and Return Values

The setting or return value is a string expression describing the fully-resolved path.

Syntax

VOIDSetSystemDB(LPCTSTR pstr);

CStringGetSystemDB(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string containing the path to the system database file.


SetOption Method (dbDAO)

CdbDBEngine::SetOption Method

Temporarily overrides values for the Microsoft Jet database engine keys in the Windows registry (Microsoft Jet workspaces only).

Syntax

VOIDSetOption(LONG lOption,

LPVARIANT pvValue);

Parameters

Type | Example | Description
LONG | lOption | A Long which specifies the registry key. Possible values are described in Remarks.
LPVARIANT | pvValue | A pointer to a variant which specifies a new value for the registry key.

Remarks

Use the SetOption method to override registry values at run-time. New values remain in effect until changed again by another SetOption call, or until the CdbDBEngine object is closed.

The following are valid Option values.

Constant | Description
dbPageTimeout | The PageTimeout key
dbSharedAsyncDelay | The SharedAsyncDelay key
dbExclusiveAsyncDelay | The ExclusiveAsyncDelay key
dbLockRetry | The LockRetry key
dbUserCommitSync | The UserCommitSync key
dbImplicitCommitSync | The ImplicitCommitSync key
dbMaxBufferSize | The MaxBufferSize key
dbMaxLocksPerFile | The MaxLocksPerFile key
dbLockDelay | The LockDelay key
dbRecycleLVs | The RecycleLVs key
dbFlushTransactionTimeout | The FlushTransactionTimeout key

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
COleVariant      vExclusiveAsyncDelay(10, VT_I2),
               vSharedAsyncDelay(15, VT_I2);
...
dben.SetOption(dbExclusiveAsyncDelay, &vExclusiveAsyncDelay);
dben.SetOption(dbSharedAsyncDelay,  &vSharedAsyncDelay);
...


CdbDBEngine Constructor (dbDAO)

CdbDBEngine Constructor

Creates an instance of the Microsoft Jet database engine.

Syntax Summary

CONSTRUCTORCdbDBEngine(const CdbDBEngine &);

CONSTRUCTORCdbDBEngine(DAODBEngine *peng,

BOOL bAddRef=FALSE);

CONSTRUCTORCdbDBEngine(BOOL bPrivate=FALSE,

BOOL bStart=TRUE,

LPCTSTR pstrIniPath=NULL,

LPCTSTR pstrDefUser=NULL,

LPCTSTR pstrDefPW=NULL,

LONG lType=dbUseJet);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax/Parameters/Remarks

CONSTRUCTORCdbDBEngine(const CdbDBEngine &);

Type | Description
const CdbDBEngine & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax/Parameters/Remarks

CONSTRUCTORCdbDBEngine(DAODBEngine *peng,

BOOL bAddRef=FALSE);

Type | Example | Description
DAODBEngine * | peng | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.

Syntax/Parameters/Remarks

CONSTRUCTORCdbDBEngine(BOOL bPrivate=FALSE,

BOOL bStart=TRUE,

LPCTSTR pstrIniPath=NULL,

LPCTSTR pstrDefUser=NULL,

LPCTSTR pstrDefPW=NULL,

LONG lType=dbUseJet);

Type | Example | Description
BOOL | bPrivate =FALSE | Optional. Determines whether the Microsoft Jet engine is private or shared. Each private engine is a new instance of DAO. A private engine is one way to create secure access to data. A shared engine is common across all instances, enabling shared workspaces and databases, for example. If TRUE, then private.
BOOL | bStart=TRUE | Optional. A Boolean. TRUEThe Microsoft Jet engine is started when this object is created. FALSEThe Microsoft Jet engine must be started explicitly with the Start method.
LPCTSTR | pstrIniPath =NULL | Optional. A pointer to a string that is a user-supplied portion of the Windows registry key containing Microsoft Jet database engine settings or parameters needed for installable ISAM databases.
LPCTSTR | pstrDefUser =NULL | Optional. A pointer to a string that is the user name used to create the default Workspace when it is initialized.
LPCTSTR | pstrDefPW =NULL | Optional. A pointer to a string that is the password used to create the default Workspace when it is initialized.
LONG | lType=dbUseJet | Optional. A value that determines whether the Workspace will be Microsoft Jet or ODBC (that is, dbUseJet or dbUseODBC).

This constructor creates an instance of the CdbDBEngine class.

This constructor is typically specified without parameters (that is, using all defaults) which makes it look like other DAO object constructors that take no parameters.

One reason to specify parameters is to create the Microsoft Jet Database Engine but postpone starting it. This enables you to acquire run-time information, or avoid run-time conflicts when starting DAO from a user DLL. Another common reason to specify parameters is to create an ODBCDirect workspace.

Usage

#include <afxole.h>
#include <dbdao.h>

// Example 1:
CdbDBEngine   dben1a;             // Create an instance using defaults.
CdbDBEngine   dben1b( dben1a );   // Copy an existing instance.

// Example 2:
/* Create an instance of CdbDBEngine without using defaults.
   Specify: a private engine; don't start it when constructed; no    IniPath, DefaultUser, or password, yet; explicitly request a    Microsoft Jet workspace.
*/

CdbDBEngine dben2(TRUE,FALSE,NULL,NULL,NULL,dbUseJet);

// After getting IniPath, DefaultUser, and DefaultPassword from the // user, set the CdbDBEngine object with those values.

   dben2.SetIniPath(lpctstrIniPath);
   dben2.SetDefaultUser(lpstrDefaultUser);
   dben2.SetDefaultPassword(lpctstrPassword);

// Now, start the engine.
   dben2.Start();


CompactDatabase Method (dbDAO)

CdbDBEngine::CompactDatabase Method

Copies and compacts a closed database, and gives you the option of changing its version, collating order, and encryption (Microsoft Jet workspaces only).

Syntax

VOIDCompactDatabase(LPCTSTR pstrOldDatabase,

LPCTSTR pstrNewDatabase,

LPCTSTR pstrDstConnect = NULL,

LONG lOptions=-1,

LPCTSTR pstrSrcConnect = NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrOldDatabase | A pointer to a string that identifies an existing, closed database. It can be a full path and file name, such as "C:\db1.mdb". If the file name has an extension, you must specify it. If your network supports it, you can also specify a network path, such as "\\server1\share1\dir1\db1.mdb".
LPCTSTR | pstrNewDatabase | A pointer to a string that is the file name (and path) of the compacted database that you're creating. You can also specify a network path. You can't use the NewDatabase argument to specify the same database file as OldDatabase.
LPCTSTR | pstrDstConnect | Optional. A pointer to a string composed of zero or more parameters separated by semicolons. This parameter is used to pass additional information to the destination database as needed. For example, collating order is specified here.
LONG | IOptions | Optional. A constant or combination of constants that indicates one or more options. The options specify the version of its data format and whether the new compacted database should be encrypted.
LPCTSTR | pstrSrcConnect | Optional. A pointer to a string composed of zero or more parameters separated by semicolons. This parameter is used to pass additional information from the source as needed.

Remarks

All users must close the database before you compact it. If the database isn't closed or isn't available for exclusive use, an error occurs.

Usage

#include <afxole.h>
#include <dbdao.h>
...
CdbDBEngine   dben;
...
dben.CompactDatabase(   _T("Northwind.mdb"), _T("Nwind2.mdb"),
                     dbLangGeneral, // This is really a string.
                     dbVersion30);


RegisterDatabase Method (dbDAO)

CdbDBEngine::RegisterDatabase Method

Enters connection information for an ODBC data source in the Windows registry. The ODBC driver needs connection information when the ODBC data source is opened during a session.

Syntax

VOIDRegisterDatabase(LPCTSTR pstrDatabase,

LPCTSTR pstrDriver,

BOOL bSilent,

LPCTSTR pstrAttributes);

Parameters

Type | Example | Description
LPCTSTR | pstrDatabase | A pointer to a string that is the name used in the OpenDatabase method. It refers to a block of descriptive information about the data source. For example, if the data source is an ODBC remote database, it could be the name of the server.
LPCTSTR | pstrDriver | A pointer to a string that is the name of the ODBC driver. This isn't the name of the ODBC driver DLL file. For example, SQL Server is a driver name, but SQLSRVR.DLL is the name of a DLL file. You must have ODBC and the appropriate driver already installed.
BOOL | bSilent | A Boolean. TRUEDoesn't display the ODBC driver dialog boxes that prompt for driver-specific information. The next parameter, Attributes, must contain all the necessary driver-specific information or the dialog boxes are displayed anyway. FALSEDisplays the ODBC driver dialog boxes.
LPCTSTR | pstrAttributes | A pointer to a string that is a list of keywords to be added to the Windows registry. The keywords are in a carriage-return-delimited string.

Usage

/*
   Register a Microsoft SQL Server data source named 'Publishers'
   in the Windows registry. (The Windows ODBC Control Panel icon
   is the preferred way to create, modify, or delete data source    names.)
   Notes:
   1) Specify IniPath, DefaultUser, DefaultPassword, etc. as
      desired in place of the ellipses.
*/
#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben(FALSE,TRUE,...,...,...,dbUseODBC); // note 1
CdbDatabase       dbsRegister;
LPCTSTR
   lpctstrAttribute =
      _T("Database=pubs\rDescription=Publishers\r
      OemToAnsi=No\rServer=Server1"),
   lpctstrNotice =
      _T("Use regedit.exe to view changes:
      HKEY_CURRENT_USER\Software\ODBC\ODBC.INI");

dbsRegister = dben.OpenDatabase(_T("Publishers"));
try
{
dben.RegisterDatabase(_T("Publishers"),
                      _T("SQL Server"),
                      TRUE, lpctstrAttribute );
printf(lpctstrNotice);
}
catch (CdbException)
{
for (long ct = 0; ct < dben.Errors.GetCount(); ct++)
   {
   printf(_T("Error #%ld: #%ld -- %s\n"),
      ct,
      dben.Errors[ct].GetNumber(),
      dben.Errors[ct].GetDescription());
   }
}


DefaultPassword Property (dbDAO)

CdbDBEngine::SetDefaultPassword Property

Sets the password used by the Microsoft Jet database engine when it is initialized.

Syntax

VOIDSetDefaultPassword(LPCTSTR pstr);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string containing a password. It can be up to 14 characters long and contain any character except ASCII 0.


DefaultUser Property (dbDAO)

CdbDBEngine::SetDefaultUser Property

Sets the user name used by the Microsoft Jet database engine when it is initialized.

Syntax

VOIDSetDefaultUser(LPCTSTR pstr);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string containing the user name. The setting for user name can be 1–20 characters long and can include alphabetic characters, accented characters, numbers, spaces, and symbols except for quotation marks ("), forward slash (/), backslash (\), brackets ([ ]), colon (:), pipe (|), less-than sign (<), greater-than sign (>), plus sign (+), equal sign (=), semicolon (;), comma (,), question mark (?), asterisk (*), leading spaces, and control characters (ASCII 00 to ASCII 31).


Start Method (dbDAO)

CdbDBEngine::Start Method

Explicitly starts the Microsoft Jet database engine rather than letting the constructor for a CdbDBEngine object implicitly start the engine.

Syntax

VOIDStart(VOID);

Remarks

Before invoking this method, set the desired CdbDBEngine object properties to customize the operation of the Microsoft Jet database engine.

Usage

#include <afxole.h>
#include <dbdao.h>
...
// Your main program
CdbDBEngine   dben(FALSE,FALSE);   // Don't start yet.
YourInitialization( &dben );      // Call your DLL.
...
// Your DLL
void YourInitialization(CdbDBEngine *pdbEngine)
{
pdbEngine->SetDefaultUser(_T("YourUserName"));
pdbEngine->SetDefaultPassword(_T("YourPassword"));
pdbEngine->SetSystemDB(_T("c:\\YourDatabase.mdb"));
pdbEngine->Start();               // Now start Jet
}


Idle Method (dbDAO)

CdbDBEngine::Idle Method

Suspends data processing, enabling the Microsoft Jet database engine to complete any pending tasks, such as memory optimization or page timeouts (Microsoft Jet workspaces only).

Syntax

VOIDIdle(LONG lOptions=-1);

Parameters

Type | Example | Description
LONG | IOptions | Optional. Specify dbRefreshCache to force any pending writes to .mdb files, and refresh memory with the most current data from the .mdb file.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbDBEngine   dben;
dben.Idle(dbRefreshCache);      // Give time to the engine.


RepairDatabase Method (dbDAO)

CdbDBEngine::RepairDatabase Method

Attempts to repair a corrupted Microsoft Jet database (Microsoft Jet databases only).

Syntax

VOIDRepairDatabase(LPCTSTR pstrDatabase);

Parameters

Type | Example | Description
LPCTSTR | pstrDatabase | A pointer to a string that contains the path and file name of an existing Microsoft Jet database file. If you omit the path, only the current directory is searched. If your system supports the uniform naming convention (UNC), you can also specify a network path, such as "\\server1\share1\dir1\db1.mdb".

Remarks

All users must close the database before you repair it. If the database isn't closed or isn't available for exclusive use, an error occurs.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbDBEngine   dben;
...                     // Attempt to repair a local database
dben.RepairDatabase(_T("db1.mdb"));


DefaultType Property (dbDAO)

CdbDBEngine::SetDefaultType, GetDefaultType Property

Sets or returns a value that indicates what type of workspace (Microsoft Jet or ODBCDirect) will be used by the next Workspace object created.

Syntax

VOIDSetDefaultType(LONG l);

LONGGetDefaultType(VOID);

Set Parameters

Type | Example | Description
LONG | l | An integer specifying the type of database engine to use as described in Remarks.

Remarks

The setting or return value can be either of the following constants.

Constant | Description
dbUseJet | Creates Workspace objects connected to the Microsoft Jet database engine.
dbUseODBC | Creates Workspace objects connected to an ODBC data source.


BeginTrans Method (dbDAO)

CdbWorkspace::BeginTrans Method

Begins a new transaction.

Syntax

VOIDBeginTrans(VOID);

Usage

#include <afxole.h>
#include <dbdao.h>

CdbWorkspace      ws;
BOOL            error;
...
ws.BeginTrans();      // Start working.
...                     // Make some changes.
if (error)
   ws.Rollback();      // Reject changes
else
   ws.CommitTrans(); // Accept changes.
ws.Close();            // Close the workspace


OpenConnection Method (dbDAO);

CdbWorkspace::OpenConnection Method

Opens a Connection object on an ODBC data source (ODBCDirect workspaces only).

Syntax

CdbConnectionOpenConnection(LPCTSTR pstrName,

LONG lOption=-1L,

BOOL bReadOnly=FALSE,

LPCTSTR pstrConnect=NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName | A pointer to a string that contains the name of a registered ODBC data source (DSN). If it doesn't refer to a valid ODBC data source name, an error occurs.
LONG | IOption | Optional. A Long value that specifies how the ODBC driver manager should prompt the user for connection information such as DSN, user name, and password. Possible values are described in Remarks.
BOOL | bReadOnly | Optional. A Boolean. TRUEOpens a Connection object for read-only access. FALSE(Default) Opens a Connection object for read/write access.
LPCTSTR | pstrConnect | Optional. A pointer to a string that contains the ODBC connect string. See the Connect property for the specific elements and syntax of this string. A prepended "ODBC;" is required. If Connect is omitted (default), the UID and/or PWD will be taken from the UserName and Password properties of the Workspace.

Remarks

The following are valid Options values.

Constant | Description
dbDriverNoPrompt | The ODBC driver manager uses the connection string provided in Name and Connect. If sufficient information is not provided, a trappable error is returned.
dbDriverPrompt | The driver manager displays the ODBC Data Sources dialog box. The connection string used to establish the connection is constructed from the DSN selected and completed by the user via the dialog boxes, or, if no DSN is chosen, the default DSN is used.
dbDriverComplete | If the Connect argument includes the DSN keyword, the driver manager uses the string as provided in Connect. Otherwise it behaves as it does when dbDriverPrompt is specified.
dbDriverCompleteRequired | Behaves like dbDriverComplete except the driver disables the prompts for any information not required to complete the connection.
dbRunAsync | Execute the method asynchronously. This constant may be used with any of the other Options constants.

The OpenConnection method is similar but not equivalent to OpenDatabase. The main difference is that OpenConnection is available only in an ODBCDirect workspace.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbDBEngine      dben(..., dbUseODBC);
CdbWorkspace      wksp;
CdbConnection   conn;
CdbRecordset      rstX;
wksp = dben.Workspaces[0L];
conn = wksp.OpenConnection(_T("ODBC;..."),
                           (dbDriverNoPrompt|dbRunAsync),
                           FALSE, T("DATABASE=SomeDB..."));
rstX = conn.OpenRecordset(...);


Close Method (dbDAO)

CdbWorkspace::Close Method

Closes an open CdbWorkspace object.

Syntax

VOIDClose(VOID);

Usage

#include <afxole.h>
#include <dbdao.h>

CdbWorkspace      ws;
BOOL            error;
...                     // Create a workspace, etc.
ws.BeginTrans();      // Start working.
...                     // Make some changes.
if (error)
   ws.Rollback();      // Reject changes
else
   ws.CommitTrans(); // Accept changes.
ws.Close();            // Close the workspace


OpenDatabase Method (dbDAO)

CdbWorkspace::OpenDatabase Method

Opens a specified database in a CdbWorkspace object.

Syntax

CdbDatabaseOpenDatabase(LPCTSTR pstrName,

BOOL bExclusive=FALSE,

BOOL bReadOnly=FALSE,

LPCTSTR pstrConnect=NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName | A pointer to a string that is the name of an existing Microsoft Jet database file, or the data source name (DSN) of an ODBC data source. See the Name property for more information about setting this value.
BOOL | bExclusive | Optional. A Boolean. TRUEOpens the database in exclusive mode. FALSE(Default) Opens the database in shared mode.
BOOL | bReadOnly | Optional. A Boolean. TRUEOpens the database with read-only access. FALSE(Default) Opens the database with read/write access.
LPCTSTR | pstrConnect | Optional. A pointer to a string that specifies various connection information, including passwords.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbWorkspace      ws;
CdbDatabase      db;
...               // Initialize ws, etc.
               // Open database in shared, read/write mode, no
               // connect information.
db = ws.OpenDatabase(_T("db1.mdb"));


CommitTrans Method (dbDAO)

CdbWorkspace::CommitTrans Method

Ends the current transaction and saves the changes.

Syntax

VOID CommitTrans (LONG lOptions=-1);

Parameters

Type | Example | Description
LONG | lOptions=-1 | Optional. In a Microsoft Jet workspace, specify dbForceOSFlush to force the database engine to immediately flush all updates to disk, instead of caching them temporarily.

Usage

#include <afxole.h>
#include <dbdao.h>
...
CdbWorkspace      ws;
BOOL            error;
...                     // Create a workspace, etc.
ws.BeginTrans();      // Start working.
...                     // Make some changes.
if (error)
   ws.Rollback();      // Reject changes
else                  // Accept changes
   ws.CommitTrans(dbForceOSFlush);
ws.Close();            // Close the workspace


UserName Property (dbDAO)

CdbWorkspace::GetUserName Property

Returns a string value that represents the owner of a Workspace object.

Syntax

CStringGetUserName(VOID);

Remarks

The UserName property represents the owner of a Workspace object.

Set the UserName property to establish the owner of the Workspace object before you append the object to the Workspaces collection.


IsolateODBCTrans Property (dbDAO)

CdbWorkspace::SetIsolateODBCTrans, GetIsolateODBCTrans Property

Sets or returns a value that indicates whether multiple transactions that involve the same Microsoft Jet-connected ODBC (Open Database Connectivity) data source are isolated (Microsoft Jet workspaces only).

Syntax

VOIDSetIsolateODBCTrans(BOOL b);

BOOLGetIsolateODBCTrans(VOID);

Set Parameters

Type | Example | Description
BOOL | b | A Boolean. TRUEIsolate transactions involving the same ODBC connection. FALSE(Default) Allow multiple transactions involving the same ODBC connection.


Rollback Method (dbDAO)

CdbWorkspace::Rollback Method

Ends the current transaction and restores the databases in the Workspace object to the state they were in when the current transaction began.

Syntax

VOIDRollback(VOID);

Usage

#include <afxole.h>
#include <dbdao.h>

CdbWorkspace      ws;
BOOL            error;
...                     // Create a workspace, etc.
ws.BeginTrans();      // Start working.
...                     // Make some changes.
if (error)
   ws.Rollback();      // Reject changes
else
   ws.CommitTrans(); // Accept changes.
ws.Close();            // Close the workspace


CreateGroup Method (dbDAO)

CdbWorkspace::CreateGroup Method

Creates a new Group object (Microsoft Jet workspaces only).

Syntax

CdbGroupCreateGroup(LPCTSTR pstrName=NULL,

LPCTSTR pstrPID=NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new Group object. See the Name property for details on valid Group names.
LPCTSTR | pstrPID | Optional. A pointer to a string containing the PID of a group account. The identifier must contain from 4 to 20 alphanumeric characters. See the PID property for more information on valid personal identifiers.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine       dben;
CdbWorkspace      ws;
CdbUser         usr;
CdbGroup         grp;
...
ws = dben.Workspaces[0L];
usr = ws.CreateUser(_T("JohnDoe"), _T("Accountant"), _T("ACCT001"));
grp = ws.CreateGroup(_T("Accountants"), _T("DEPT_01_99"));
grp.Users.Append(usr);
usr.Groups.Append(grp);


CreateDatabase Method (dbDAO)

CdbWorkspace::CreateDatabase Method

Creates a new Database object, saves the database to disk, and returns an opened Database object (Microsoft Jet workspaces only).

Syntax

CdbDatabaseCreateDatabase(LPCTSTR pstrName,

LPCTSTR pstrConnect,

LONG lOption=-1);

Parameters

Type | Example | Description
LPCTSTR | pstrName | A pointer to a string up to 255 characters long that is the name of the database file that you're creating. It can be the full path and file name, such as "C:\db1.mdb". If you don't supply a file name extension, .mdb is appended. If your network supports it, you can also specify a network path, such as "\\server1\share1\dir1\db1". You can only create .mdb database files with this method.
LPCTSTR | pstrConnect | A pointer to a string that specifies various connection information, including passwords.
LONG | lOption | Optional. A constant or combination of constants that indicates one or more options. See Settings in core topic for details.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
CdbWorkspace      wrkDefault;
CdbDatabase      dbsNew;

wrkDefault = dben.Workspaces(0L);
/* Create a new encrypted database with the specified
   (dbLangGeneral) collating order.
*/
dbsNew = wrkDefault.CreateDatabase(_T("NewDB.mdb"),
                                 dbLangGeneral, dbEncrypt);
...
dbsNew.Close();


Name Property (dbDAO)

CdbWorkspace::SetName, GetName Property

Sets or returns a user-defined name for a CdbWorkspace object. For an object not appended to a collection, this property is read/write.

Settings and Return Values

The setting or return value is a string that specifies a name. The name must start with a letter and can contain a maximum of 64 characters. It can include numbers and underscore characters but can't include punctuation or spaces.

Syntax

VOIDSetName(LPCTSTR pstr);

StringGetName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains the name of the CdbWorkspace object.

Remarks

Create a Workspace object using the Name and UserName properties to establish a named, password-protected session. The session creates a scope in which you can open multiple databases and conduct one instance of nested transactions. Use the Close method to terminate a session.


CreateUser Method (dbDAO)

CdbWorkspace::CreateUser Method

Creates a new User object (Microsoft Jet workspaces only).

Syntax

CdbUserCreateUser(LPCTSTR pstrName=NULL,

LPCTSTR pstrPID=NULL,

LPCTSTR pstrPassword=NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new User object. See the Name property for details on valid User names.
LPCTSTR | pstrPID | Optional. A pointer to a string containing the personal identifier (PID) of a user account. The PID must contain from 4 to 20 alphanumeric characters. See the PID property for more information on valid personal identifiers.
LPCTSTR | pstrPassword | Optional. A pointer to a string containing the password for the new User object. The password can be up to 14 characters long and can include any characters except the ASCII character 0 (null). See the Password property for more information on valid passwords.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine       dben;
CdbWorkspace      ws;
CdbUser         usr;
CdbGroup         grp;
...
ws = dben.Workspaces[0L];
usr = ws.CreateUser(_T("JohnDoe"), _T("Accountant"), _T("ACCT001"));
grp = ws.CreateGroup(_T("Accountants"), _T("DEPT_01_99"));
grp.Users.Append(usr);
usr.Groups.Append(grp);


CdbWorkspace Constructor (dbDAO)

CdbWorkspace Constructor

Syntax Summary

CONSTRUCTORCdbWorkspace(VOID);

CONSTRUCTORCdbWorkspace(const CdbWorkspace &);

CONSTRUCTORCdbWorkspace(DAOWorkspace *pwrk,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax/Parameters/Remarks

CONSTRUCTORCdbWorkspace(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax/Parameters/Remarks

CONSTRUCTORCdbWorkspace(const CdbWorkspace &);

Type | Description
const CdbWorkspace & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax/Parameters/Remarks

CONSTRUCTORCdbWorkspace(DAOWorkspace *pwrk,

BOOL bAddRef=FALSE);

Type | Example | Description
DAOWorkspace * | pwrk | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Close Method (dbDAO)

CdbDatabase::Close Method

Closes an open CdbDatabase object.

Syntax

VOIDClose(VOID);

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDatabase   db;
db = dben.OpenDatabase(_T("MyDatabase.mbd"));
...                  // Do some work.
db.Close();        // Close the database


Version Property (dbDAO)

CdbDatabase::GetVersion Property

Returns a CString that indicates the data format version of an open database. This property setting is read-only.

Syntax

CStringGetVersion(VOID);


Execute Method (dbDAO)

CdbDatabase::Execute Method

Runs an SQL statement on a specified Database object.

Syntax

VOIDExecute(LPCTSTR pstrQuery,

LONG lOption=-1);

Parameters

Type | Example | Description
LPCTSTR | pstrQuery | A pointer to a string that is an SQL statement.
LONG | lOption | Optional. A constant or combination of constants that determines the data integrity characteristics of the query, as specified in Remarks.

Remarks

The following are valid Option values.

Constant | Description
dbDenyWrite | Denies write permission to other users (Microsoft Jet workspaces only).
dbInconsistent | (Default) Executes inconsistent updates (Microsoft Jet workspaces only).
dbConsistent | Executes consistent updates (Microsoft Jet workspaces only).
dbSQLPassThrough | Executes an SQL pass-through query. Setting this option passes the SQL statement to an ODBC database for processing (Microsoft Jet workspaces only).
dbFailOnError | Rolls back updates if an error occurs (Microsoft Jet workspaces only).
dbSeeChanges | Generates a run-time error if another user is changing data you are editing (Microsoft Jet workspaces only).

Usage

#include <afxole.h>
#include <dbdao.h>

CdbWorkspace      ws;
CdbDatabase      db;
...                  // Initialize ws, db, etc.

ws.BeginTrans();      // Start working.
db.Execute(_T("SELECT * FROM PARTS"),  dbFailOnError);
                     // Make some changes.
ws.CommitTrans();       // Accept changes.
ws.Close();            // Close the workspace


Name Property (dbDAO)

CdbDatabase::GetName Property

Returns a CString that contains the user-defined name for a CdbDatabase object.

The return value is a string that starts with a letter and can contain a maximum of 64 characters. It can include numbers and underscore characters but can't include punctuation or spaces.

Syntax

CStringGetName(VOID);


Synchronize Method (dbDAO)

CdbDatabase::Synchronize Method

Synchronizes two replicas (Microsoft Jet databases only).

Syntax

VOIDSynchronize(LPCTSTR pstrReplica,

LONG lType=-1);

Parameters

Type | Example | Description
LPCTSTR | pstrReplica | A pointer to a string that contains the path to the target replica with which this database will be synchronized. The .mdb file name extension is optional.
LONG | lType | Optional. A constant indicating which direction to synchronize changes between the two databases, as specified in Settings.

Settings

You can use the following constants in the second argument. You can use one of the first three constants with or without the fourth constant.

Constant | Description
dbRepExportChanges | Sends changes from database object to pstrReplica.
dbRepImportChanges | Sends changes from pstrReplica to database object.
dbRepImpExpChanges | (Default) Sends changes from database object to pstrReplica, and vice-versa, also known as bi-directional exchange.
dbRepSyncInternet | Exchanges data between files connected by an Internet pathway.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngin   dben;
CdbDatabase   db;
...                        // Initialize db, etc.
db = dben.OpenDatabase(_T("OutOfDateReplica.mdb"));
db.Synchronize(_T("file:\\website\UpToDateReplica.mdb"),
                  (dbRepImpExpChanges|dbRepSyncInternet));


QueryTimeout Property (dbDAO)

CdbDatabase::SetQueryTimeout, GetQueryTimeout Property

Sets or returns a value that specifies the number of seconds to wait before a timeout error occurs when a query is executed on an ODBC data source.

Syntax

VOIDSetQueryTimeout(SHORT s);

SHORTGetQueryTimeout(VOID);

Set Parameters

Type | Example | Description
SHORT | s | An integer specifying the number of seconds before DAO times out. The default value is 60.


ReplicaID Property (dbDAO)

CdbDatabase::GetReplicaID Property

Returns a 16-byte GUID string whose value uniquely identifies a database replica or Design Master (Microsoft Jet workspaces only).

Syntax

CStringGetReplicaID(VOID);

Remarks

The Microsoft Jet database engine automatically generates this value when you create a new replica.


Updatable Property (dbDAO)

CdbDatabase::GetUpdatable Property

Returns a Boolean value that indicates whether changes can be made to the Database object. TRUE indicates that the object can be changed or updated; FALSE, that it cannot.

Syntax

BOOLGetUpdatable(VOID);


Transactions Property (dbDAO)

CdbDatabase::GetTransactions Property

Returns a Boolean value that indicates whether an object supports the recording of a series of changes that can later be rolled back (canceled) or committed (saved). TRUE indicates that the object supports transactions. Snapshot-type Recordset objects always return FALSE.

Syntax

BOOLGetTransactions(VOID);


CreateTableDef Method (dbDAO)

CdbDatabase::CreateTableDef Method

Creates a new TableDef object (Microsoft Jet workspaces only).

Syntax

CdbTableDefCreateTableDef(LPCTSTR pstrName=NULL,

LONG lAttributes=-1,

LPCTSTR pstrSource=NULL,

LPCTSTR pstrConnect=NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new TableDef object. See the Name property for details on valid TableDef names.
LONG | lAttributes | Optional. A constant or combination of constants that indicates one or more characteristics of the new TableDef object. See the Attributes property for more information.
LPCTSTR | pstrSource | Optional. A pointer to a string containing the name of a table in an external database that is the original source of the data. The source string becomes the SourceTableName property setting of the new TableDef object.
LPCTSTR | pstrConnect | Optional. A pointer to a string containing information about the source of an open database, a database used in a pass-through query, or a linked table. See the Connect property for more information about valid connection strings.

Remarks

If you omit one or more of the optional parts when you use the CreateTableDef method, you can set the corresponding property before you append the new object to a collection. After you append the object, you can alter some but not all of its properties. See the individual property topics for more details.

Usage

#include <afxole.h>
#include <dbdao.h>
   // Create a new TableDef object in the Biblio.mdb database.
CdbDbenine    dben;
CdbTableDef tdfTitle;
CdbField       fldComments;
CdbDatabase dbsBiblio;

dbsBiblio = dben.Workspaces[0L].OpenDatabase(_T("Biblio.mdb"));
   // Create new TableDef.
tdfTitle = dbsBiblio.CreateTableDef(_T("Title Detail"));
   // Create and append field to tdfTitle.
fldComments = tdfTitle.CreateField(_T("Comments"), dbMemo);
tdfTitle.Fields.Append(fldComments);
   // Append TableDef to TableDefs collection.
dbsBiblio.TableDefs.Append(tdfTitle);


CdbDatabase Constructor (dbDAO)

CdbDatabase Constructor

Creates an instance or a copy of a Database object.

Syntax Summary

CONSTRUCTORCdbDatabase(VOID);

CONSTRUCTORCdbDatabase(const CdbDatabase &);

CONSTRUCTORCdbDatabase(DAODatabase *pdb,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax/Parameters/Remarks

CONSTRUCTORCdbDatabase(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax/Parameters/Remarks

CONSTRUCTORCdbDatabase(const CdbDatabase &);

Type | Description
const CdbDatabase & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax/Parameters/Remarks

CONSTRUCTORCdbDatabase(DAODatabase *pdb,

BOOL bAddRef=FALSE);

Type | Example | Description
DAODatabase * | pdb | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


CollatingOrder Property (dbDAO)

CdbDatabase::GetCollatingOrder Property

Returns a value that specifies the sequence of the sort order for string comparison or sorting.

Syntax

LONGGetCollatingOrder(VOID);

Remarks

GetCollatingOrder returns a Long with one of the following values:

Constant | Description
dbSortGeneral | Use the General (English, French, German, Portuguese, Italian, and Modern Spanish) sort order.
dbSortArabic | Use the Arabic sort order.
dbSortCyrillic | Use the Russian sort order.
dbSortCzech | Use the Czech sort order.
dbSortDutch | Use the Dutch sort order.
dbSortGreek | Use the Greek sort order.
dbSortHebrew | Use the Hebrew sort order.
dbSortHungarian | Use the Hungarian sort order.
dbSortIcelandic | Use the Icelandic sort order.
dbSortJapanese | Use the Japanese sort order.
dbSortNeutral | Use the neutral sort order.
dbSortNorwdan | Use the Norwegian or Danish sort order.
dbSortPDXIntl | Use the Paradox International sort order.
dbSortPDXNor | Use the Paradox Norwegian or Danish sort order.
dbSortPDXSwe | Use the Paradox Swedish or Finnish sort order.
dbSortPolish | Use the Polish sort order.
dbSortSpanish | Use the Spanish sort order.
dbSortSwedFin | Use the Swedish or Finnish sort order.
dbSortTurkish | Use the Turkish sort order.
dbSortUndefined | The sort order is undefined or unknown.


RecordsAffected Property (dbDAO)

CdbDatabase::GetRecordsAffected Property

Returns the number of records affected by the most recently invoked Execute method.

The return value is an integer from 0 to the number of records affected by the most recently invoked Execute method on the Database object.

Syntax

LONGGetRecordsAffected(VOID);


MakeReplica Method (dbDAO)

CdbDatabase::MakeReplica Method

Makes a new replica from another database replica (Microsoft Jet workspaces only).

Syntax

VOIDMakeReplica(LPCTSTR pstrPath,

LPCTSTR pstrDescription,

LONG lOptions=-1);

Parameters

Type | Example | Description
LPCTSTR | pstrPath | A pointer to a string that contains the path and file name of the new replica. If the replica is an existing file name, then an error occurs.
LPCTSTR | pstrDescription | A pointer to a string that describes the replica you are creating.
LONG | lOptions | Optional. A constant or combination of constants that specifies characteristics of the replica you are creating, as specified in Settings.

Settings

You can use one or more of the following constants in the third argument.

Constant | Description
dbRepMakePartial | Creates a partial replica.
dbRepMakeReadOnly | Prevents users from modifying the replicable objects of the new replica; however, when you synchronize the new replica with another member of the replica set, design and data changes will be propagated to the new replica.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngin   dben;
CdbDatabase   db;
...                        // Initialize db, etc.
db = dben.OpenDatabase(_T("OriginalReplica.mdb"));
db.MakeReplica(_T("NewReplica.mdb"),
               _T("Copy of OriginalReplica.mdb"),
               dbRepMakeReadOnly);


CreateRelation Method (dbDAO)

CdbDatabase::CreateRelation Method

Creates a new Relation object (Microsoft Jet workspaces only).

Syntax

CdbRelationCreateRelation(LPCTSTR pstrName=NULL,

LPCTSTR pstrTable=NULL,

LPCTSTR pstrForiegn=NULL,

LONG lAttributes=-1);

Parameters

Type | Example | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new Relation object. See the Name property for details on valid relation names.
LPCTSTR | pstrTable | Optional. A pointer to a string that names the primary table in the relation. If the table doesn't exist before you append the Relation object, a run-time error occurs.
LPCTSTR | pstrForiegn | Optional. A pointer to a string that names the foreign table in the relation. If the table doesn't exist before you append the Relation object, a run-time error occurs.
LONG | lAttributes | Optional. A constant or combination of constants that contains information about the relationship type. See the Attributes property for details.

Usage

#include <afxole.h>
#include <dbdao.h>
...
CdbDBEngine   dben;
CdbDatabase   dbs;
CdbRelation   rel;

dbs = dben.OpenDatabase(_T("Acme.mdb"));
rel = dbs.CreateRelation(_T("EmpSecurity"),_T("Employees"),
                         _T("SocialSecurity", dbRelationUnique);


CreateQueryDef Method (dbDAO)

CdbDatabase::CreateQueryDef Method

Creates a new QueryDef object in a specified Database object.

Syntax

CdbQueryDefCreateQueryDef(LPCTSTR pstrName=NULL,

LPCTSTR pstrSQL=NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new QueryDef.
LPCTSTR | pstrSQL | Optional. A pointer to a string that is an SQL statement defining the QueryDef. If you omit this argument, you can define the QueryDef by setting its SQL property before or after you append it to a collection.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDatabase   db;
CdbQueryDef   qd1;
...                        // Initialize db, etc.
qd1 = CreateQueryDef(_T("QD_PARTS"), _T("SELECT * FROM PARTS"));


OpenRecordset Method (dbDAO)

CdbDatabase::OpenRecordset Method

Creates a new Recordset object and appends it to the Recordsets collection.

Syntax

CdbRecordsetOpenRecordset(LPCTSTR pstrName,

LONG lType=-1,

LONG lOptions=-1,

LONG lLockEdit=-1);

Parameters

Type | Example | Description
LPCTSTR | pstrName | A pointer to a string specifying the source of the records for the new Recordset. The source can be a table name, a query name, or an SQL statement that returns records. For table-type Recordset objects in Microsoft Jet databases, the source can only be a table name.
LONG | lType | Optional. A constant that indicates the type of Recordset to open, as specified in Settings in the core topic.
LONG | lOptions | Optional. A combination of constants that specify characteristics of the new Recordset, as listed in Settings in the core topic.
LONG | lLockEdit | Optional. A constant that determines the locking for the Recordset, as specified in Settings in the core topic.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDatabase      db;
CdbRecordset      rst;
CString         strSql = _T("SELECT * FROM PARTS");
...                              // Initialize db, etc.
rst = db.OpenRecordset((LPCTSTR)strSql, dbOpenDynaset,                               dbDenyWrite, dbPessimistic);


DesignMasterID Property (dbDAO)

CdbDatabase::SetDesignMasterID, GetDesignMasterID Property

Sets or returns a 16-byte GUID string whose value uniquely identifies the Design Master in a replica set (Microsoft Jet workspaces only).

Remarks

You should set the DesignMasterID property only if you need to move the current Design Master. Setting this property makes a specific replica in the replica set the Design Master.

Never create a second Design Master in a replica set. The existence of a second Design Master can result in the loss of data.

Syntax

VOIDSetDesignMasterID(LPCTSTR pstrMasterID);

CStringGetDesignMasterID(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstrMasterID | A pointer to a string that contains the 16-byte GUID of a Design Master.


CreateProperty Method (dbDAO)

CdbDatabase::CreateProperty Method

Creates a new user-defined Property object (Microsoft Jet workspaces only).

Syntax

CdbPropertyCreateProperty(LPCTSTR pstrName=NULL,

LONG lType=-1,

LPVARIANT pvValue=NULL,

BOOL bDDL=FALSE);

Parameters

Type | Example | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new Property object. See the Name property for details on valid property names.
LONG | lType | Optional. A constant that defines the data type of the new Property object. See the Type property for valid data types.
LPVARIANT | pvValue | Optional. A pointer to a Variant containing the initial property value. See the Value property for details.
BOOL | bDDL=FALSE | Optional. A Boolean that indicates whether or not the Property is a DDL object. If TRUE, users can't change or delete this Property object unless they have dbSecWriteDef permission.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDatabase      dbs;
CdbProperty      prop;
COleVariant      vVal(FALSE, VT_BOOL);

// Initialize dbs, etc.
// Create a property that says whether this database contains
//   information that must be reported quarterly.

dbs  = dben.OpenDatabase(...);
prop = dbs.CreateProperty(_T("QuarterlyReportRequired"),                dbBoolean, &vVal, FALSE);
dbs.Properties.Append( prop );  // Append property.


Connect Property (dbDAO)

CdbDatabase::SetConnect, GetConnect Property

Sets or returns a value that provides information about the source of an open database. For Database objects not yet appended to a collection, this property setting is read/write.

Syntax

VOIDSetConnect(LPCTSTR pstrConnect);

CStringGetConnect(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstrConnect | A pointer to a string that specifies additional parameters to pass to ODBC or installable ISAM drivers. Use semicolons to separate parameters.

Remarks

The Connect property specifies the database type and any other parameters used to connect to external databases. See the Database object topic for more details.


StillExecuting Property (dbDAO)

CdbConnection::GetStillExecuting Property

Indicates whether or not a query that was started with an OpenRecordset or Execute method call with the dbRunAsync option has finished executing (ODBCDirect only).

Settings and Return Values

The setting or return value is a Boolean that is TRUE to indicate the query is still executing, and FALSE to indicate that the query has completed.

Syntax

BOOLGetStillExecuting(VOID);

Remarks

Use the StillExecuting property to determine if a query executed using the dbRunAsync option is complete. While the StillExecuting property is TRUE, the associated object cannot be accessed.


CdbConnection Constructor (dbDAO)

CdbConnection Constructor

Syntax Summary

CONSTRUCTORCdbConnection(VOID);

CONSTRUCTORCdbConnection(const CdbConnection &);

CONSTRUCTORCdbConnection(DAOConnection *pconn,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax/Parameters/Remarks

CONSTRUCTORCdbConnection(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax/Parameters/Remarks

CONSTRUCTORCdbConnection(const CdbConnection &);

Type | Description
const CdbConnection & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax/Parameters/Remarks

CONSTRUCTORCdbConnection(DAOConnection *pconn,

BOOL bAddRef=FALSE);

Type | Example | Description
DAOConnection * | pconn | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Close Method (dbDAO)

CdbConnection::Close Method

Closes an open Connection object.

Syntax

VOIDClose(VOID);

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
CdbConnection   conn;
CdbWorkspace      ws;
...
ws = dben.CreateWorkspace(..., dbUseODBC);
conn = ws.OpenConnection(...);
...               // Do some work.
conn.Close();
ws.Close();


CreateQueryDef Method (dbDAO)

CdbConnection::CreateQueryDef Method

Creates a new QueryDef object in the specified Connection object.

Syntax

CdbQueryDefCreateQueryDef(LPCTSTR pstrName=NULL,

LPCTSTR pstrSQL=NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName =NULL | Optional. A pointer to a string that uniquely names the new QueryDef.
LPCTSTR | pstrSQL =NULL | Optional. A pointer to a string that is an SQL statement defining the QueryDef. If you omit this argument, you can define the QueryDef by setting its SQL property before or after you append it to a collection.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbQueryDef       qd;
CdbConnection   conn;
LPCTSTR          lpctsrSQL =
   _T("SELECT SALARY FROM EMPLOYEES WHERE LASTNAME = 'SMITH'");
...
qd = conn.CreateQueryDef(_T("SALARYDEF"), lpctsrSQL);
conn.Execute(_T("SALARYDEF"), dbFailOnError);


Execute Method (dbDAO)

CdbConnection::Execute Method

Runs an action query or executes an SQL statement on a specified Connection object.

Syntax

VOIDExecute(LPCTSTR pstrQuery,

LONG lOption=-1);

Parameters

Type | Example | Description
LPCTSTR | pstrQuery | A pointer to a string that is an SQL statement or the Name property value of a QueryDef object.
LONG | lOption | Optional. A constant or combination of constants that determines the data integrity characteristics of the query, as specified in Remarks.

Remarks

The following are valid values for Option.

Constant | Description
dbDenyWrite | Denies write permission to other users (Microsoft Jet workspaces only).
dbInconsistent | (Default) Executes inconsistent updates (Microsoft Jet workspaces only).
dbConsistent | Executes consistent updates (Microsoft Jet workspaces only).
dbSQLPassThrough | Executes an SQL pass-through query. Setting this option passes the SQL statement to an ODBC database for processing (Microsoft Jet workspaces only).
dbFailOnError | Rolls back updates if an error occurs (Microsoft Jet workspaces only).
dbSeeChanges | Generates a run-time error if another user is changing data you are editing (Microsoft Jet workspaces only).
dbRunAsync | Executes the query asynchronously (ODBCDirect Connection and QueryDef objects only).
dbExecDirect | Executes the statement without first calling SQLPrepare ODBC API function (ODBCDirect Connection and QueryDef objects only).

Usage

#include <afxole.h>
#include <dbdao.h>
CdbQueryDef       qd;
CdbConnection   conn;
LPCTSTR          lpctsrSQL =
   _T("SELECT SALARY FROM EMPLOYEES WHERE LASTNAME = 'SMITH'");
...
qd = conn.CreateQueryDef(_T("SALARYDEF"), lpctsrSQL);
conn.Execute(_T("SALARYDEF"), dbFailOnError);


OpenRecordset Method (dbDAO)

CdbConnection::OpenRecordset Method

Creates a new Recordset object and appends it to the Recordsets collection.

Syntax

CdbRecordsetOpenRecordset(LPCTSTR pstrName,

LONG lType=-1,

LONG lOptions=-1,

LONG lLockType=-1);

Parameters

Type | Example | Description
LPCTSTR | pstrName | A pointer to a string specifying the source of the records for the new Recordset. The source can be a table name, a query name, or an SQL statement that returns records. For table-type Recordset objects in Microsoft Jet databases, the source can only be a table name.
LONG | lType | Optional. A constant that indicates the type of Recordset to open, as specified in Settings in the core topic.
LONG | lOptions | Optional. A combination of constants that specify characteristics of the new Recordset, as listed in Settings in the core topic.
LONG | lLockType | Optional. A constant that determines the locking for the Recordset, as specified in Settings in the core topic.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbConnection   conn;
CdbRecordset      rst;
CString         strSql = _T("SELECT * FROM PARTS");
...                           // Initialize conn, etc.
rst = conn.OpenRecordset((LPCTSTR)strSql, dbOpenDynaset,                                  dbDenyWrite, dbPessimistic);


Connect Property (dbDAO)

CdbConnection::GetConnect Property

Returns a CString whose value provides information about the source of an open database.

Syntax

CStringGetConnect(VOID);


Name Property (dbDAO)

CdbConnection::GetName Property

Returns a user-defined name for a CdbConnection object.

The return value is a CString expression that specifies a name. The name must start with a letter and can contain a maximum of 64 characters. It can include numbers and underscore characters but can't include punctuation or spaces.

Syntax

CStringGetName(VOID);


Cancel Method (dbDAO)

CdbConnection::Cancel Method

Cancels execution of a pending asynchronous method call (ODBCDirect workspaces only).

Syntax

VOIDCancel(VOID);

Remarks

Use the Cancel method to terminate execution of an asynchronous Execute or OpenConnection method call (that is, the method was invoked with the dbRunAsync option).

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben(...,dbUseODBC);
CdbWorkspace      wrkMain;
CdbConnect      conMain;

wrkMain = dben.CreateWorkspace("ODBCWorkspace",
               _T("admin"), _T(""), dbUseODBC);
// Open the connection asynchronously.
conMain = wrkMain.OpenConnection("Publishers",
               (dbDriverNoPrompt | dbRunAsync),
               FALSE,
               _T("ODBC;DATABASE=pubs;UID=sa;PWD=;DSN=Publishers"));
// Wait a few seconds...
// If the connection has not been made, quit.
if (conMain.StillExecuting())
   conMain.Cancel();
else
   {      // Use the Connection object conMain.
   ...
   conMain.Close();
   }
wrkMain.Close();


QueryTimeout Property (dbDAO)

CdbConnection::SetQueryTimeout, GetQueryTimeout Property

Sets or returns a value that specifies the number of seconds to wait before a timeout error occurs when a query is executed on an ODBC data source.

Syntax

SHORTGetQueryTimeout(VOID);

VOIDSetQueryTimeout(SHORT s);

Set Parameters

Type |  | Description
SHORT | s | The number of seconds to wait. The default value is 60.


RecordsAffected Property (dbDAO)

CdbConnection::GetRecordsAffected Property

Returns the number of records affected by the most recently invoked Execute method.

The return value is an integer from 0 to the number of records affected by the most recently invoked Execute method on the Connection object.

Syntax

LONGGetRecordsAffected(VOID);


Updatable Property (dbDAO)

CdbConnection::GetUpdatable Property

Returns a Boolean value that indicates whether changes can be made to a CdbConnection object. TRUE indicates that the object can be changed or updated; FALSE, that it cannot.

Syntax

BOOLGetUpdatable(VOID);


Database Property (dbDAO)

CdbConnection::GetDatabase Property

Returns the Database object that corresponds to this connection (ODBCDirect only).

Syntax

CdbDatabaseGetDatabase(VOID);


Bookmarkable Property (dbDAO)

CdbRecordset::GetBookmarkable Property

Returns a Boolean TRUE if the Recordset object supports bookmarks (which you can set using the Bookmark property).

Syntax

BOOLGetBookmarkable(VOID);


RecordCount Property (dbDAO)

CdbRecordset::GetRecordCount Property

Returns the number of records accessed in a Recordset object, or the total number of records in a table-type Recordset or TableDef object.

Syntax

LONGGetRecordCount(VOID);

Remarks

Use the RecordCount property to determine how many records in a Recordset or TableDef object have been accessed. The RecordCount property doesn't indicate how many records are contained in a dynaset-, snapshot-, or forward-only–type Recordset object until all records have been accessed. Once the last record has been accessed, the RecordCount property indicates the total number of undeleted records in the Recordset or TableDef object. To force the last record to be accessed, use the MoveLast method on the Recordset object. You can also use an SQL Count function to determine the approximate number of records your query will return.

Note that using the MoveLast method to populate a newly opened Recordset negatively impacts performance. Unless it is necessary to have an accurate RecordCount as soon as you open a Recordset, it's better to wait until you populate the Recordset with other portions of code before checking the RecordCount property.


FillCache Method (dbDAO)

CdbRecordset::FillCache Method

Fills all or a part of a local cache for a Recordset object that contains data from a Microsoft Jet-connected ODBC data source (Microsoft Jet-connected ODBC databases only).

Syntax

VOIDFillCache(LONG lRows=-1, CdbBookmark *pbm=NULL);

Parameters

Type | Example | Description
LONG | lRows | Optional. An integer that specifies the number of rows to store in the cache. If you omit this argument, the value is determined by the CacheSize property setting.
CdbBookmark * | pbm=NULL | Optional. Pointer to a bookmark. The cache is filled starting from the record indicated by this bookmark. If you omit this argument, the cache is filled starting from the record indicated by the CacheStar t property.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBE   ngine      dben(..., dbUseODBC);
CdbDatabase      dbs;
CdbRecordset      rst;
CdbBookmark      book;

dbs = dben.OpenDatabase(_T("ODBC;..."));
rst = dbs.OpenRecordset(..., dbOpenDynaset);
if (rst.Bookmarkable())
{
   // Remember the current record position.
book = rst.GetBookmark();
   // Start the cache from the current position.
rst.SetCacheStart(book);
   // The cache will hold 25 records.
rst.SetCacheSize(25);
rst.FillCache();
   // Do some work...
rst.MoveNext();
   // Get a few more records.
book = rst.GetBookmark();
rst.FillCache(5, &book);
...
}


AddNew Method (dbDAO)

CdbRecordset::AddNew Method

Creates a new record for an updatable Recordset object.

Syntax

VOIDAddNew(VOID);

Remarks

Use the AddNew method to create and add a new record in the CdbRecordset object. This method sets the fields to default values, and if no default values are specified, it sets the fields to NULL (the default values specified for a table-type Recordset).

After you modify the new record, use the Update method to save the changes and add the record to the Recordset. No changes occur in the database until you use the Update method.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rst;
...
rst.AddNew();   // Create an empty recordset.
...               // Set the values of the recordset fields
rst.Update()      // Save your changes.
rst.Close();      // Close the recordset.


Close Method (dbDAO)

CdbRecordset::Close Method

Closes an open Recordset object.

Syntax

VOIDClose(VOID);

Usage

#include <afxole.h>
#include <dbdao.h>
...
CdbRecordset      rst;
COleVariant      vVal;
rst.OpenRecordset(...);   // Open some recordset
vVal = rst.GetField(0L);   // Get the first field
rst.Close();              // Close the recordset


Clone Method (dbDAO)

CdbRecordset::Clone Method

Creates a duplicate of the original Recordset object.

Syntax

CdbRecordsetClone(VOID);

Remarks

Clone returns an instance of CdbRecordset.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rstOriginal, rstNew;
...   // Open the original recordset.
   // Make a duplicate of it.
rstNew = rstOriginal.Clone();


SetField Method (dbDAO)

CdbRecordset::SetField Method

SetField modifies the value of a Field (that is, table column) in a Recordset to the supplied value.

Syntax

VOIDSetField( LPCTSTR pstrIndex, LPVARIANT pv);

VOIDSetField( CString &str,LPVARIANT pv) ;

VOIDSetField( LONG lIndex, LPVARIANT pv);

VOIDSetField( COleVariant &vIndex,LPVARIANT pv);

Parameters

Type | Example | Description
LPCTSTR | pstrIndex | A pointer to a string that contains the name of the desired Field.
CString & | str | A reference to a CString that contains the name of the desired Field.
LONG | lIndex | An integer that is the index of the desired Field, starting from the leftmost Field and counting from zero.
COleVariant & | vIndex | A reference to a COleVariant with a value that is the index of the desired Field, starting from the leftmost Field and counting from zero, or a string containing the name of the Field.
LPVARIANT | pv | Pointer to a COleVariant whose value will be inserted into the specified Field.

Remarks

SetField is only available in dbDAO. It is provided as a more efficient way of setting the value of a Field, other than accessing the Recordset object's Fields collection, then invoking the SetValue method:

COleVariant    vName(_T("Smith"), VT_BSTRT),
            vValue(100, VT_I4);
...
recordset.Fields[_T("LastName")].SetValue(&vName);
recordset.Fields[0L].SetValue(&vValue);

Usage

#include <afxole.h>
#include <dbdao.h>

COleVariant    vName(_T("Smith"), VT_BSTRT),
            vValue(100, VT_I4);
...
recordset.SetField(_T("LastName"), &vName); // set the LastName field
recordset.SetField(0L, &vValue);   // set the first field


CopyQueryDef Method (dbDAO)

CdbRecordset::CopyQueryDef Method

Copies the QueryDef used to create the Recordset object (Microsoft Jet workspaces only).

Syntax

CdbQueryDefCopyQueryDef(VOID);

Remarks

The CopyQueryDef method returns a CdbQueryDef object variable that represents the QueryDef object you want to copy.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
CdbRecordset    rst;
CdbDatabase      dbs;
CdbQueryDef      qd;
CString         strSQL = _T("SELECT * FROM PARTS");
...
dbs = dben.OpenDatabase(_T("Northwind.mdb"));
   // Get a recordset based on a query.
rst = dbs.OpenRecordset(strSQL);
   // Get a copy of the query that built the recordset.
qd = rst.CopyQueryDef();     // Copy the queryDef


GetRows Method (dbDAO)

CdbRecordset::GetRows Method

Retrieves multiple rows from a Recordset object.

Syntax

COleVariantGetRows(LONG lRows=-1);

Parameters

Type | Example | Description
LONG | lRows | The number of rows to retrieve. The default is all rows.

Returns

GetRows returns a two-dimensional array into a COleVariant. The first subscript identifies the field and the second identifies the row number. Subscripts are zero-based.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rst;
COleVariant      vRows, vVal;
LONG            lIndex[2], lMax = 10;
HRESULT         hr;

...                           // Open a recordset, etc.
vRows = rst.GetRows(lMax);   // Get 10 rows from the recordset.
lIndex[0] = 0;               // Index the first field.
                           // Index rows 0 through 9.
for (lIndex[1] = 0; lIndex[1] < lMax; lIndex[1]++)
{                           // Get the field.
hr = SafeArrayGetElement(vRows.parray, &lIndex, &vVal);
...                           // Process the field in vVal.
}


OpenRecordset Method (dbDAO)

CdbRecordset::OpenRecordset Method

Creates a new Recordset object and appends it to the Recordsets collection.

Syntax

CdbRecordsetOpenRecordset(LONG lType=-1, LONG lOption=-1);

Parameters

Type | Example | Description
LONG | lType | Optional. A constant that indicates the type of Recordset to open as listed in Settings.
LONG | lOption | Optional. A combination of constants that specify characteristics of the new Recordset as listed in Settings.

Settings

Use the following values for Type.

Constant | Description
dbOpenTable | Opens a table-type Recordset object (Microsoft Jet workspaces only).
dbOpenDynamic | Opens a dynamic-type Recordset object, which is similar to an ODBC dynamic cursor. (ODBCDirect workspaces only)
dbOpenDynaset | Opens a dynaset-type Recordset object, which is similar to an ODBC keyset cursor.
dbOpenSnapshot | Opens a snapshot-type Recordset object, which is similar to an ODBC static cursor.
dbOpenForwardOnly | Opens a forward-only-type Recordset object.

Use the following values for Option.

Constant | Description
dbAppendOnly | Allows users to append new records to the Recordset, but prevents them from editing or deleting existing records (Microsoft Jet dynaset-type Recordset only).
dbSQLPassThrough | Passes an SQL statement to a Microsoft Jet-connected ODBC data source for processing (Microsoft Jet snapshot-type Recordset only).
dbSeeChanges | Generates a run-time error if one user is changing data that another user is editing (Microsoft Jet dynaset-type Recordset only). This is useful in applications where multiple users have simultaneous read/write access to the same data.
dbDenyWrite | Prevents other users from modifying or adding records (Microsoft Jet Recordset objects only).
dbDenyRead | Prevents other users from reading data in a table (Microsoft Jet table-type Recordset only).
dbForwardOnly | Creates a forward-only Recordset (Microsoft Jet snapshot-type Recordset only). It is provided only for backward compatibility, and you should use the dbOpenForwardOnly constant in the type argument instead of using this option.
dbReadOnly | Prevents users from making changes to the Recordset (Microsoft Jet only). The dbReadOnly constant in the lockedits argument replaces this option, which is provided only for backward compatibility.
dbRunAsync | Runs an asynchronous query (ODBCDirect workspaces only).
dbExecDirect | Runs a query by skipping SQLPrepare and directly calling SQLExecDirect (ODBCDirect workspaces only). Use this option only when you’re not opening a Recordset based on a parameter query. For more information, see the "Microsoft ODBC 3.0 Programmer’s Reference."
dbInconsistent | Allows inconsistent updates (Microsoft Jet dynaset-type and snapshot-type Recordset objects only).
dbConsistent | Allows only consistent updates (Microsoft Jet dynaset-type and snapshot-type Recordset objects only).

Remarks

The constants dbConsistent and dbInconsistent are mutually exclusive. Using both causes an error.

Note The core topic says the LockEdits parameter is available for all OpenRecordset methods. The CdbRecordset::OpenRecordset method actually applies to Microsoft Jet workspaces only. The LockEdits parameter actually applies to ODBCDirect workspaces only and is not available in this method.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbDBEngine      dben;
CdbDatabase      dbs;
CdbRecordset      rst, rst2;

dbs = dben.OpenDatabase(_T("Northwind.mdb"));
rst = dbs.OpenRecordset(_T("SELECT * FROM EMPLOYEES"),dbOpenDynaset);
   // Get more selective.
rst.SetFilter(_T("LASTNAME >= 'M'");
rst2 = rst.OpenRecordset();


PercentPosition Property (dbDAO)

CdbRecordset::SetPercentPosition, GetPercentPosition Property

Sets or returns a value indicating the approximate location of the current record in the Recordset object based on a percentage of the records in the Recordset.

The setting or return value is a Float between 0.0 and 100.00.

Syntax

VOIDSetPercentPosition(FLOAT f);

FLOATGetPercentPosition(VOID);

Set Parameters

Type | Example | Description
FLOAT | f | A Float between 0.0 and 100.00.

Remarks

To indicate or change the approximate position of the current record in a Recordset object, you can check or set the PercentPosition property. When working with a dynaset- or snapshot-type Recordset object opened directly from a base table, first populate the Recordset object by moving to the last record before you set or check the PercentPosition property. If you use the PercentPosition property before fully populating the Recordset object, the amount of movement is relative to the number of records accessed as indicated by the RecordCount property. Use the MoveLast method to move to the last record.

Note that using the PercentPosition property to move the current record to a specific record in a Recordset object isn't recommended—the Bookmark property is better suited for this task.


RecordStatus Property (dbDAO)

CdbRecordset::SetRecordStatus, GetRecordStatus Property

Set or returns a value indicating whether and how the current record will be involved in the next optimistic batch update (ODBCDirect workspaces only).

Syntax

SHORTGetRecordStatus(VOID);

VOIDSetRecordStatus(SHORT i);

Set Parameters

Type | Example | Description
SHORT | i | A Short with one or more of the values specified in Settings.

Settings

Constant | Description
dbRecordUnmodified | (Default) The record has not been modified or has been updated successfully.
dbRecordModified | The record has been modified and not updated in the database.
dbRecordNew | The record has been inserted with the AddNew method, but not yet inserted into the database.
dbRecordDeleted | The record has been deleted, but not yet deleted in the database.
dbRecordDBDeleted | The record has been deleted locally and in the database.

Remark

The core topic states that this property returns a Long. However, the CdbRecordset object's member function is declared as Short.


Delete Method (dbDAO)

CdbRecordset::Delete Method

Deletes the current record in an updatable Recordset object.

Syntax

VOIDDelete(VOID);

Remarks

For ODBCDirect workspaces, the type of driver determines whether Recordset objects are updatable and therefore support the Delete method.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rst;
...
rst.MoveLast();         // Make the last record the current record.
rst.Delete();         // Delete the current record.
rst.Close();            // Close the recordset.


Cancel Method (dbDAO)

CdbRecordset::Cancel Method

Cancels execution of a pending asynchronous method call (ODBCDirect workspaces only).

Syntax

VOIDCancel(VOID);

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
CdbWorkspace      ws;
CdbDatabase      dbs;
CdbRecordset      rst;
LPTSTR            szSelect =       // Two queries...
                  "SELECT LastName, FirstName "
                  "FROM Authors WHERE LastName = 'Smith';"                  "SELECT Title, ISBN FROM Titles WHERE "
                  "Pub_ID = 9999";
...
ws  = dben.CreateWorkspace(...,dbUseODBC);
dbs = ws.OpenDatabase(...);
rst    = dbs.OpenRecordset(szSelect);
while( rst.NextRecordset())
{   ...            // Process each query...
   if (Error)
      rst.Cancel();
   else
      rst.Update();
   ...
}
 rst.Close();


LastModified Property (dbDAO)

CdbRecordset::GetLastModified Property

Returns a bookmark indicating the most recently added or changed record.

Syntax

CdbBookmarkGetLastModified(VOID);


Requery Method (dbDAO)

CdbRecordset::Requery Method

Updates the data in a Recordset object by re-executing the query on which the object is based.

Syntax

VOIDRequery(CdbQueryDef *pq = NULL);

Parameters

Type | Example | Description
CdbQueryDef * | pq = NULL | Optional. Pointer to a QueryDef that represents the Name property value of a QueryDef object (Microsoft Jet workspaces only).

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset recordset;
...
recordset.Edit();         // Make some changes
...
recordset.Update;         // Save changes
recordset.Requery();     // Refresh the recordset


Bookmarkable Property (dbDAO)

CdbRecordset::GetDateCreated Property

Returns the date and time that the base table was created.

Syntax

COleDateTimeGetDateCreated(VOID);


Update Method (dbDAO)

CdbRecordset::Update Method

Saves the contents of the current record, and any changes you've made to it, to an updatable Recordset object.

Syntax

VOIDUpdate(short sType = dbUpdateRegular,

VARIANT_BOOL bForce = FALSE);

Parameters

Type | Example | Description
SHORT | sType = dbUpdateRegular | Optional. A constant indicating the type of update, as specified in Settings (ODBCDirect workspaces only).
VARIANT_BOOL | bForce = FALSE | Optional. A Boolean value indicating whether or not to force the changes into the database, regardless of whether the underlying data has been changed by another user since the AddNew, Delete, or Edit call. If TRUE, the changes are forced and changes made by other users are simply overwritten. If FALSE (default), changes made by another user while the update is pending will cause the update to fail for those changes that are in conflict. No error occurs, but the BatchCollisionCount and BatchCollisions properties will indicate the number of conflicts and the rows affected by conflicts, respectively (ODBCDirect workspaces only).

Settings

You can use the following values for the first argument. You can use the non-default values only if batch updating is enabled.

Constant | Description
dbUpdateRegular | (Default) Pending changes aren’t cached and are written to disk immediately.
dbUpdateBatch | All pending changes in the update cache are written to disk.
dbUpdateCurrentRecord | Only the current record’s pending changes are written to disk.

Usage

#include <afxole.h>
#include <dbdao.h>

COleVariant       vVal(_T("LastName"), VT_BSTRT);
CdbRecordset      rst;
...               // Intialize recordset etc.
rst.Edit();
rst.SetField( 0L, vVal);      // Edit the first field.
rst.Update(dbUpdateCurrentRecord, TRUE);


Transactions Property (dbDAO)

CdbRecordset::GetTransactions Property

Returns a Boolean value that indicates whether an object supports transactions.

GetTransactions returns TRUE if the object supports transactions. Snapshot- and forward-only–type Recordset objects always return FALSE.

Syntax

BOOLGetTransactions(VOID);

Remarks

You can use the Transactions property with dynaset- or table-type Recordset objects in a Microsoft Jet workspace, and with any Recordset object in an ODBCDirect workspace.


EditMode Property (dbDAO)

CdbRecordset::GetEditMode Property

Returns a value that indicates the state of editing for the current record.

Syntax

SHORTGetEditMode(VOID);

Remarks

The possible return values are:

Constant | Description
dbEditNone | No editing operation is in progress.
dbEditInProgress | The Edit method has been invoked, and the current record is in the copy buffer.
dbEditAdd | The AddNew method has been invoked, and the current record in the copy buffer is a new record that hasn't been saved in the database.


Filter Property (dbDAO)

CdbRecordset::SetFilter, GetFilter Property

Sets or returns a value that determines the records included in a subsequently opened Recordset object. The value is a string that contains the WHERE clause of an SQL statement without the reserved word WHERE.

Syntax

CStringGetFilter(VOID);

VOIDSetFilter(LPCTSTR pstr);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains the WHERE clause of an SQL statement without the reserved word WHERE.


Index Property (dbDAO)

CdbRecordset::SetIndex, GetIndex Property

Sets or returns a value that indicates the name of the current Index object in a table-type Recordset object.

Settings and Return Values

The setting or return value is a string expression that evaluates to the name of an Index object in the Indexes collection of a table-type Recordset created by a TableDef object.

GetIndex returns a CString data type.

Syntax

VOIDSetIndex(LPCTSTR pstr);

CStringGetIndex(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A string containing the name of an Index object.

Remarks

Records in base tables aren't stored in any particular order. Setting the Index property changes the order of records returned from the database; it doesn't affect the order in which the records are stored.


Type Property (dbDAO)

CdbRecordset::GetType Property

Returns the operational type or data type of an object.

Syntax

SHORTGetType(VOID);

Remarks

The possible return values for a CdbRecordset are:

Constant | Recordset type
dbOpenTable | Table (Microsoft Jet workspaces only)
dbOpenDynamic | Dynamic (ODBCDirect workspaces only)
dbOpenDynaset | Dynaset
dbOpenSnapshot | Snapshot
dbOpenForwardOnly | Forward-only


Name Property (dbDAO)

CdbRecordset::GetName Property

Returns a user-defined name for a Recordset object.

The return value is a CString that specifies a name. The name must start with a letter and can contain a maximum of 64 characters. It can include numbers and underscore characters but can't include punctuation or spaces.

Syntax

CStringGetName(VOID);


NextRecordset Method (dbDAO)

CdbRecordset::NextRecordset Method

Gets the next set of records, if any, returned by a multiple part select query in an OpenRecordset call, and returns a Boolean value indicating whether one or more additional records are pending (ODBCDirect workspaces only).

Syntax

BOOLNextRecordset(VOID);

Returns

A Boolean variable. TRUE indicates the next set of records is available in Recordset; FALSE indicates that no more records are pending and Recordset is now empty.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
CdbWorkspace      ws;
CdbDatabase      dbs;
CdbRecordset      rst;
LPTSTR            szSelect =       // Two queries...
                  "SELECT LastName, FirstName "
                  "FROM Authors WHERE LastName = 'Smith';"                  "SELECT Title, ISBN FROM Titles WHERE "
                  "Pub_ID = 9999";
...
ws = dben.CreateWorkspace(...,dbUseODBC);
dbs = ws.OpenDatabase(...);
rst    = dbs.OpenRecordset(szSelect);
while( rst.NextRecordset())
{   ...            // Process each query...
   if (Error)
      rst.Cancel();
   else
      rst.Update();
   ...
}
 rst.Close();


FindFirst Method (dbDAO)

CdbRecordset::FindFirst, FindLast, FindNext, FindPrevious Methods

Locates the first, last, next, or previous record in a dynaset- or snapshot-type Recordset object that satisfies the specified criteria, then makes that record the current record.

Syntax

VOIDFindFirst( LPCTSTRpstrCriteria);

VOIDFindLast( LPCTSTRpstrCriteria);

VOIDFindNext( LPCTSTRpstrCriteria);

VOIDFindPrevious( LPCTSTRpstrCriteria);

Parameters

Type | Example | Description
LPCTSTR | pstrCriteria | A pointer to a string expression (like the WHERE clause in an SQL statement without the word WHERE) used to locate the record.

Remarks

If you want to include all the records in your search, not just those that meet a specific condition, use the Move methods to move from record to record. To locate a record in a table-type Recordset, use the Seek method.

If a record matching the criteria isn't located, the current record pointer is undetermined, and the NoMatch property is set to TRUE. If the Recordset contains more than one record that satisfies the criteria, FindFirst locates the first occurrence, FindNext locates the next occurrence, and so on.

Usage

#include <afxole.h>
#include <dbdao.h>
...
CdbBookmark      bmHere;
CdbRecordset      rstCustomers;
...
// Save current record position.
bmHere = rstCustomers.GetBookmark();
// Search for a name in the recordset.
rstCustomers.FindFirst(_T("Name = 'Ms. Schmidt'"));
// If not found go back to saved record position.
if (rstCustomers.GetNoMatch())
   rstCustomers.SetBookmark( &bmHere );


Restartable Property (dbDAO)

CdbRecordset::GetRestartable Property

Returns a Boolean value that indicates whether a Recordset object supports the Requery method, which re-executes the query on which the Recordset object is based.

The return value is TRUE if the Recordset object supports the Requery method. Table-type Recordset objects always return FALSE.

Syntax

BOOLGetRestartable(VOID);


NoMatch Property (dbDAO)

CdbRecordset::GetNoMatch Property

Returns a value indicating whether a particular record was found using the Seek method or one of the Find methods. TRUE indicates that the desired record was not found.

Syntax

BOOLGetNoMatch(VOID);

Remarks

When you open or create a Recordset object, its NoMatch property is set to FALSE.


Updatable Property (dbDAO)

CdbRecordset::GetUpdatable Property

Returns a Boolean value that indicates whether the Recordset can be updated.

The return value is TRUE if the object can be changed or updated. (Snapshot- and forward-only–type Recordset objects always return FALSE.)

Syntax

BOOLGetUpdatable(VOID);


CacheSize Property (dbDAO)

CdbRecordset::SetCacheSize, GetCacheSize Property

Sets or returns the number of records retrieved from an ODBC data source that will be cached locally.

Settings and Return Values

The setting or return value must be between 5 and 1200, but not greater than available memory will allow. A typical value is 100. A setting of 0 turns off caching.

Syntax

VOIDSetCacheSize(LONG l);

LONGGetCacheSize(VOID);

Set Parameters

Type | Example | Description
LONG | l | A Long which specifies the number of records that will be cached locally.


BatchCollisionCount Property (dbDAO)

CdbRecordset::GetBatchCollisionCount Property

Returns the number of records that did not complete the last batch update, or 0 if all records were successfully updated (ODBCDirect workspaces only).

Syntax

LONGGetBatchCollisionCount(VOID);

Remarks

This property indicates how many records encountered collisions or otherwise failed to update during the last batch update attempt. The value of this property corresponds to the number of bookmarks in the BatchCollisions property.

If you set the working Recordset object's Bookmark property to bookmark values in the BatchCollisions array, you can move to each record that failed to complete the most recent batch update operation.

After the collision records are corrected, a batch-mode Update method can be called again. At this point DAO attempts another batch update, and the BatchCollisions property again reflects the set of records that failed the second attempt. Any records that succeeded in the previous attempt are not sent in the current attempt, because they now have a RecordStatus property of dbRecordUnmodified. This process can continue as long as collisions occur, or until you abandon the updates and close the result set.


StillExecuting Property (dbDAO)

CdbRecordset::GetStillExecuting Property

Indicates whether or not an asynchronous operation (that is, a method called with the dbRunAsync option) has finished executing (ODBCDirect workspaces only).

The return value is a Boolean that is TRUE if the query is still executing, and FALSE if the query has completed.

Syntax

BOOLGetStillExecuting(VOID);

Remarks

Use the StillExecuting property to determine if the most recently called asynchronous MoveLast or OpenRecordset method is complete. While the StillExecuting property is TRUE, any returned object cannot be accessed.

When you use the NextRecordset method to complete processing a Recordset, the StillExecuting property is reset to TRUE while subsequent result sets are retrieved.


GetField Method (dbDAO)

CdbRecordset::GetField Method

GetField returns the value of a Field (that is, a table column) in a Recordset. The Field is identified by either its name (that is, column name), or its index (that is, cardinal position in the row).

Syntax

COleVariantGetField( LPCTSTRpstrIndex );

COleVariantGetField( CString &str);

COleVariantGetField( LONGlIndex );

COleVariantGetField( COleVariant &vIndex);

Parameters

Type | Example | Description
LPCTSTR | pstrIndex | A pointer to a string that contains the name of the desired Field.
CString & | str | A reference to a CString that contains the name of the desired Field.
LONG | lIndex | An integer that is the index of the desired Field, starting from the leftmost Field and counting from zero.
COleVariant & | vIndex | A reference to a COleVariant with a value that is the index of the desired Field, starting from the leftmost Field and counting from zero, or a string containing the name of the Field.

Remarks

GetField is only available in dbDAO. It is provided as a more efficient way of getting the value of a Field, other than accessing the Recordset object's Fields collection, then invoking the GetValue method:

COleVariant vValbyName, vValbyIndex;
vValbyName = recordset.Fields[_T("fieldname")].GetValue();
vValbyIndex = recordset.Fields[index].GetValue();

Usage

#include <afxole.h>
#include <dbdao.h>

COleVariant vVal;
   // Initialize a recordset, etc.
   // Get the value of the 'LastName' field.
vVal = recordset.GetField(_T("LastName"));
   // Get the value of the third field.
vVal = recordset.GetField(2L);


Edit Method (dbDAO)

CdbRecordset::Edit Method

Copies the current record from an updatable Recordset object to the copy buffer for subsequent editing.

Syntax

VOIDEdit(VOID);

Remarks

Once you use the Edit method, changes made to the current record's fields are copied to the copy buffer. After you make the desired changes to the record, use the Update method to save your changes. The current record remains current after you use Edit.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rst;
...               // Open the recordset.
rst.Edit();      // Edit the current record.
...               // Make changes to the record.
rst.Update();   // Save the change.
...
rst.Close();      // Close the recordset.


LastUpdated Property (dbDAO)

CdbRecordset::GetLastUpdated Property

Returns the date and time of the most recent change made to the base table.

Syntax

COleDateTimeGetLastUpdated(VOID);


Sort Property (dbDAO)

CdbRecordset::SetSort, GetSort Property

Sets or returns the sort order for records in a Recordset object.

GetSort returns the sort order in a CString.

Syntax

VOIDSetSort(LPCTSTR pstr);

CStringGetSort(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains the ORDER BY clause of an SQL statement without the reserved words ORDER BY.

Remarks

You can use the Sort property with dynaset- and snapshot-type Recordset objects.

When you set this property for an object, sorting occurs when a subsequent Recordset object is created from that object. The Sort property setting overrides any sort order specified for a QueryDef object.

The Sort property doesn't apply to table-type Recordset objects. To sort a table-type Recordset object, use the Index property.

In many cases, it's faster to open a new Recordset object using an SQL statement that includes the sorting criteria.


GetRowsEx Method (dbDAO)

CdbRecordset::GetRowsEx Method

The GetRowsEx method retrieves multiple rows and allows you to specify the data types of the fields stored in your application variables.

The GetRowsEx method is a performance improvement by dbDAO and MFC DAO to avoid the necessity to retrieve all data as variants and then convert to native types.

Syntax

LONGGetRowsEx(LPVOID pvBuffer,

LONG cbRow,

LPDAORSETBINDING prb,

LONG cBinding,

LPVOID pvVarBuffer = NULL,

LONG cbVarBuffer = 0,

LONG lRows = -1);

Parameters

Type | Example | Description
LPVOID | pvBuffer | Pointer to buffer in which to store returned rows.
LONG | cbRow | Length of row in bytes.
LPDAORSETBINDING | prb | Pointer to binding structure.
LONG | cBinding | Number of bindings.
LPVOID | pvVarBuffer = NULL | Optional. Pointer to buffer in which to store variable-length data.
LONG | cbVarBuffer = 0 | Optional. Length in bytes of pvVarBuffer.
LONG | lRows | Optional. Number of rows requested.

GetRowsEx returns a Long which indicates the number of records actually retrieved.

Remarks

GetRowsEx is only available in dbDAO.

The DAORSETBINDING structure specifies how data is to be copied from the rows to the memory buffer. A separate binding structure must be filled in for each field retrieved.

Note Each time GetRowsEx retrieves a set of records, it retrieves the last record of the previous set again. For example, if you retrieve five records at a time, GetRowsEx will first retrieve records 1 through 5. The next time it will retrieve records 5 through 10. The time after that, records 10 through 15, and so on. Notice that records 5 and 10 are retrieved twice.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rst;
COleVariant      vRows;
int               n;
LONG            lIndex[2];
HRESULT         hr;
DAORSETBINDING   dsbind;
TCHAR            Buffer[512], VarBuffer[256];
...                        // Open a recordset, fill in binding                            // structure, etc.
vRows = GetRowsEx(&Buffer, cbRow, &dsbind, cBinding,
                  &VarBuffer, sizeof(VarBuffer), 10);
lIndex[0] = 0;            // Index of the 1st field.
lIndex[1] = 1;            // Index of the 2nd row.
                        // Get the field (assume an integer).
hr = SafeArrayGetElement(vRows.parray, &lIndex, &n);


BOF Property (dbDAO)

CdbRecordset::GetBOF, GetEOF Property

The BOF property returns TRUE if the current record position is before the first record, and FALSE if the current record position is on or after the first record in a Recordset object.

The EOF property returns TRUE if the current record position is after the last record, and FALSE if the current record position is on or before the last record in a Recordset object.

Syntax

BOOLGetBOF(VOID);

BOOLGetEOF(VOID);


ValidationRule Property (dbDAO)

CdbRecordset::GetValidationRule Property

Returns a value that validates the data in a field as it's changed or added to a table (Microsoft Jet workspaces only).

The return value is a CString that describes a comparison in the form of an SQL WHERE clause without the WHERE reserved word.

Syntax

CStringGetValidationRule(VOID);


Bookmark Property (dbDAO)

CdbRecordset::SetBookmark, GetBookmark Property

Sets or returns a bookmark that uniquely identifies the current record in a Recordset object or sets the current record in a Recordset object to a valid bookmark.

Settings and Return Values

The setting or return value is a string expression or variant expression that evaluates to a valid bookmark. (Data type is Variant array of Byte data.)

GetBookmark() returns a CdbBookmark object.

Syntax

CdbBookmarkGetBookmark(VOID);

VOIDSetBookmark(class CdbBookmark );

Set Parameters

Type | Description
class CdbBookmark | A bookmark of the desired record position.


ValidationText Property (dbDAO)

CdbRecordset::GetValidationText Property

Returns a CString value that specifies the text of the message that your application displays if the value of a Field object doesn't satisfy the validation rule specified by the ValidationRule property setting (Microsoft Jet workspaces only).

Syntax

CStringGetValidationText(VOID);


CacheStart Property (dbDAO)

CdbRecordset::SetCacheStart, GetCacheStart Property

Sets or returns a value that specifies the bookmark of the first record in a dynaset-type Recordset object containing data to be locally cached from a Microsoft Jet-connected ODBC data source (Microsoft Jet workspaces only).

GetCacheStart returns a CdbBookmark.

Syntax

VOIDSetCacheStart(CdbBookmark &pbm);

CdbBookmarkGetCacheStart(VOID);

Set Parameters

Type | Example | Description
CdbBookmark & | pbm | A CdbBookmark reference of the first record to be cached.

Remarks

Data caching improves the performance of an application that retrieves data from a remote server through dynaset-type Recordset objects.


AbsolutePosition Property (dbDAO)

CdbRecordset::SetAbsolutePosition, GetAbsolutePosition Property

Sets or returns the relative record number of a Recordset object's current record.

Settings and Return Values

The setting or return value is a Long from 0 to one less than the number of records in the Recordset object. It corresponds to the ordinal position of the current record in the Recordset object specified by the object.

Syntax

VOIDSetAbsolutePosition(LONG l);

LONGGetAbsolutePosition(VOID);

Set Parameters

Type | Example | Description
LONG | l | A Long containing a relative record number from 0 to one less than the number of records in the Recordset.

Remarks

You can use the AbsolutePosition property to position the current record pointer to a specific record based on its ordinal position in a dynaset- or snapshot-type Recordset object. You can also determine the current record number by checking the AbsolutePosition property setting.

Because the AbsolutePosition property value is zero-based, you cannot set it to a value greater than or equal to the number of populated records; doing so causes a trappable error. You can determine the number of populated records in the Recordset object by checking the RecordCount property setting. The maximum allowable setting for the AbsolutePosition property is the value of the RecordCount property minus 1.


BatchSize Property (dbDAO)

CdbRecordset::SetBatchSize, GetBatchSize Property

Sets or returns the number of statements sent back to the server in each batch update (ODBCDirect workspaces only).

Syntax

VOIDSetBatchSize(LONG l);

LONGGetBatchSize(VOID);

Set Parameters

Type | Example | Description
LONG | l | A Long that indicates the number of batched statements sent to the server in a single batch update. The default value is 15.

Remarks

This property can be changed at any time. If a database server doesn't support statement batching, you can set this property to 1, causing each statement to be sent separately.


Move Method (dbDAO)

CdbRecordset::Move Method

Moves the position of the current record in a Recordset object.

Syntax

VOIDMove( LONG lRows, CdbBookmark *bm=NULL );

Parameters

Type | Example | Description
LONG | lRows | A signed value specifying the number of rows the position will move. If rows is greater than 0, the position is moved forward (toward the end of the file). If rows is less than 0, the position is moved backward (toward the beginning of the file).
CdbBookmark * | bm | Pointer to a bookmark. If specified, Move begins relative to this bookmark. If not specified (that is, the default value of NULL is used), Move begins from the current record.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbBookmark bm;
...
recordset.Move( 10 );         // Move forward 10 records
recordset.Move( -5, &bm );   // Move back 5 records relative to
                           // a given bookmark.


LockEdits Property (dbDAO)

CdbRecordset::SetLockEdits, GetLockEdits Property

Sets or returns a Boolean value indicating the locking that is in effect during editing.

Syntax

BOOLGetLockEdits(VOID);

VOIDSetLockEdits(BOOL b);

Set Parameters

Type Example Description
BOOL b A Boolean value indicating the locking that is in effect:

TRUE(Default) Pessimistic locking is in effect. The 2K page containing the record you're editing is locked as soon as you use the Edit method.

FALSEOptimistic locking is in effect for editing. The 2K page containing the record is not locked until the Update method is executed.


CancelUpdate Method (dbDAO)

CdbRecordset::CancelUpdate Method

Cancels any pending updates for the Recordset object.

Syntax

VOIDCancelUpdate(short sType = dbUpdateRegular);

Parameters

Type | Example | Description
SHORT | sType = dbUpdateRegular | Optional. A constant indicating the type of update (ODBCDirect workspaces only).

The following are valid values for Type.

Constant | Description
dbUpdateRegular | (Default) Pending changes aren’t cached and are written to disk immediately.
dbUpdateBatch | All pending changes in the update cache are written to disk.

Remarks

You can use the CancelUpdate method to cancel any pending updates resulting from an Edit or AddNew operation.

Usage

#include <afxole.h>
#include <dbdao.h>
...
BOOL            bOK = TRUE;
CdbRecordset      rst;
...
rst.AddNew();            // Begin to add a record
if (bOK)                  // Is it OK to add a record?
   rst.Update();         // yes: Complete the addition
else                     // no: Abort the addition
   rst.CancelUpdate(dbUpdateRegular);


MoveFirst Method (dbDAO)

CdbRecordset::MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Moves to the first, last, next, or previous record in a specified Recordset object and makes that record the current record.

Syntax

VOIDMoveFirst(VOID);

VOIDMoveLast(LONG lOptions=-1);

VOIDMoveNext(VOID);

VOIDMovePrevious(VOID);

Parameters

Type | Example | Description
LONG | lOptions=-1 | Optional. If set to the dbRunAsync constant, the method call is asynchronous. You can use the Cancel method to terminate execution of the asynchronous MoveLast method call. You can use the StillExecuting property to determine when the Recordset is fully populated.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDatabase      dbs;
CdbRecordset      rst;
...                        // Initiliaze dbs, etc.
rst = dbs.OpenDatabase(strSQL);
while (!rst.GetEOF())
{
   ...                  // Do some processing.
   rst.MoveNext();      // Get the next record.
}


CdbRecordset Constructor (dbDAO)

CdbRecordset Constructor

Syntax Summary

CONSTRUCTORCdbRecordset(VOID);

CONSTRUCTORCdbRecordset(const CdbRecordset &);

CONSTRUCTORCdbRecordset(DAORecordset *prs,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax/Parameters/Remarks

CONSTRUCTORCdbRecordset(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax/Parameters/Remarks

CONSTRUCTORCdbRecordset(const CdbRecordset &);

Type | Description
const CdbRecordset & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax/Parameters/Remarks

CONSTRUCTORCdbRecordset(DAORecordset *prs,

BOOL bAddRef=FALSE);

Type | Example | Description
DAORecordset * | prs | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Seek Method (dbDAO)

CdbRecordset::Seek Method

Locates the record in an indexed table-type Recordset object that satisfies the specified criteria for the current index and makes that record the current record (Microsoft Jet workspaces only).

Syntax

VOIDSeek(LPCTSTR pstrComparison,

LONG lNumFields,

COleVariant cKey,

...);

Parameters

Type | Example | Description
LPCTSTR | pstrComparison | One of the following string expressions: <, <=, =, >=, or >.
LONG | lNumFields | The number of key arguments that follow. This argument may have a value from 1 to 13. (The maximum value of this parameter is defined by DAO_MAXSEEKFIELDS.)
COleVariant | cKey, ... | One or more values corresponding to fields in the Recordset object's current index, as specified by its Index property setting. Seek accepts an unspecified number of arguments, as indicated by the ellipsis symbol ("..."), however you may only have a maximum of 13 key arguments.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
CdbDatabase      dbs;
CdbRecordset      rst;
...
   // Open a table-type recordset.
rst = dbs.OpenRecordset(..., dbOpenTable);
   // Define current index as the LastName index.
rst.SetIndex(_T("LastName"));
   // Seek first record with last name equal to Smith
rst.Seek("=", 1, _T("Smith"));


UpdateOptions Property (dbDAO)

CdbRecordset::SetUpdateOptions, GetUpdateOptions Property

Sets or returns a value that indicates how the WHERE clause is constructed for each record during a batch update, and whether the batch update should use an UPDATE statement or a DELETE followed by an INSERT (ODBCDirect workspaces only).

Syntax

VOIDSetUpdateOptions(LONG l);

LONGGetUpdateOptions(VOID);

Set Parameters

Type | Example | Description
LONG | l | A Long with one or more of the values specified in Settings.

Settings

Constant | Description
dbCriteriaKey | (Default) Uses just the key column(s) in the WHERE clause.
dbCriteriaModValues | Uses the key column(s) and all updated columns in the WHERE clause.
dbCriteriaAllCols | Uses the key column(s) and all the columns in the WHERE clause.
dbCriteriaTimeStamp | Uses just the timestamp column if available (will generate a run-time error if no timestamp column is in the result set).
dbCriteriaDeleteInsert | Uses a set of DELETE and INSERT statements for each modified row.
dbCriteriaUpdate | (Default) Uses an UPDATE statement for each modified row.


DefaultValue Property (dbDAO)

CdbField::SetDefaultValue, GetDefaultValue Property

Sets or returns the default value of a CdbField object.

Syntax

VOIDSetDefaultValue(LPCTSTR pstr);

CStringGetDefaultValue(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains a maximum of 255 characters. It can be either text or an expression. If the property setting is an expression, it can't contain user-defined functions, Microsoft Jet database engine SQL aggregate functions, or references to queries, forms, or other Field objects.


CreateProperty Method (dbDAO)

CdbField::CreateProperty Method

Creates a new user-defined Property object.

Syntax

CdbPropertyCreateProperty(LPCTSTR pstrName=NULL,

LONG lType=-1,

LPVARIANT pvValue=NULL,

BOOL bDDL=FALSE);

Parameters

Type | Example | Description
LPCTSTR | pstrName | Optional. A pointer to a string that contains the name of the new property.
LONG | lType | Optional. The type of the new property. Its value may be one of those listed under Types in the core topic.
LPVARIANT | pvValue | Optional. A Variant variable containing the initial property value. See the Value property for details.
BOOL | bDDL=FALSE | Optional. A Boolean indicating whether or not the created Property object is a Data Definition Language object. If TRUE, the created Property object can't be changed or deleted unless the user has dbSecWriteDef permission. The default is FALSE.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEngine      dben;
CdbDatabase      dbs;
CdbField         fld;
CdbProperty      prop;
COleVariant      vVal(FALSE, VT_BOOL);

// Initialization...
// Create a property that says whether this field is required.
fld = dbs.Fields[3L];         // Get the 4th field.
prop = fld.CreateProperty(_T("Required"), dbBoolean, &vVal, FALSE);
fld.Properties.Append( prop );


FieldSize Method (dbDAO)

CdbField::FieldSize Method

Returns the number of bytes used in the database (rather than in memory) of a Memo or an OLE Object Field object in the Fields collection of a Recordset object.

Syntax

LONG FieldSize(VOID);

Remarks

Returns the number of bytes used in the database.

Usage

#include <afxole.h>
#include <dbdao.h>

LONG            length;
CdbField         fld;
CdbRecordset      rs;
...                        // Initialize as needed
fld = rs.Fields[0L];         // Get the first field
length = fld.FieldSize();   // Get the field size


OriginalValue Property (dbDAO)

CdbField::GetOriginalValue Property

Returns the value of a Field in the database that existed when the last batch update began (ODBCDirect workspaces only).

Syntax

COleVariantGetOriginalValue(VOID);

Remarks

During an optimistic batch update, a collision may occur where a second client modifies the same field and record in between the time the first client retrieves the data and the first client's update attempt. The OriginalValue property contains the value of the field at the time the last batch update began. If this value does not match the value actually in the database when the batch update attempts to write to the database, a collision occurs. When this happens, the new value in the database will be accessible through the VisibleValue property.


AppendChunk Method (dbDAO)

CdbField::AppendChunk Method

Appends data from a string expression to a Memo or Long Binary (OLE Object) Field object in the Fields collection of a Recordset object.

Syntax

VOIDAppendChunk(LPVARIANT pv);

Parameters

Type | Example | Description
LPVARIANT | pv | A pointer to a variant whose value will be appended to the Fields collection.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rs;
CdbField         fld;
COleVariant      vVal("abcdefghijklmnop", VT_BSTRT);
...                        // Initialize recordset, etc.
fld = rs.Fields[0];      // Get a field.
fld.AppendChunk(&vVal);    // Append the chunk.


ForeignName Property (dbDAO)

CdbField::SetForeignName, GetForeignName Property

Sets or returns a value that specifies the name of the CdbField object in a foreign table that corresponds to a field in a primary table for a relationship (Microsoft Jet workspaces only).

Syntax

VOIDSetForeignName(LPCTSTR pstr);

CStringGetForeignName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains the name of the field in a foreign table.

Remarks

Only a CdbField object that belongs to the CdbFields collection of a CdbRelation object can support the ForeignName property.


CollatingOrder Property (dbDAO)

CdbField::GetCollatingOrder Property

Returns a Long value that specifies the sequence of the sort order in text for string comparison or sorting (Microsoft Jet workspaces only).

Syntax

LONGGetCollatingOrder(VOID);

Remarks

The possible return values are:

Constant | Sort Order
dbSortGeneral | General (English, French, German, Portuguese, Italian, and Modern Spanish)
dbSortArabic | Arabic
dbSortChineseSimplified | Simplified Chinese
dbSortChineseTraditional | Traditional Chinese
dbSortCyrillic | Russian
dbSortCzech | Czech
dbSortDutch | Dutch
dbSortGreek | Greek
dbSortHebrew | Hebrew
dbSortHungarian | Hungarian
dbSortIcelandic | Icelandic
dbSortJapanese | Japanese
dbSortKorean | Korean
dbSortNeutral | Neutral
dbSortNorwDan | Norwegian or Danish
dbSortPDXIntl | Paradox International
dbSortPDXNor | Paradox Norwegian or Danish
dbSortPDXSwe | Paradox Swedish or Finnish
dbSortPolish | Polish
dbSortSlovenian | Slovenian
dbSortSpanish | Spanish
dbSortSwedFin | Swedish or Finnish
dbSortThai | Thai
dbSortTurkish | Turkish
dbSortUndefined | Undefined or unknown


CdbField Constructor (dbDAO)

CdbField Constructor

Syntax Summary

CONSTRUCTORCdbField(VOID);

CONSTRUCTORCdbField(const CdbField &);

CONSTRUCTORCdbField(DAOField *pfld,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax/Parameters/Remarks

CONSTRUCTORCdbField(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax/Parameters/Remarks

CONSTRUCTORCdbField(const CdbField &);

Type | Description
const CdbField & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax/Parameters/Remarks

CONSTRUCTORCdbField(DAOField *pfld,

BOOL bAddRef=FALSE);

Type | Example | Description
DAOField * | pfld | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Type Property (dbDAO)

CdbField::SetType, GetType Property

Sets or returns a value that indicates the data type of an CdbField object.

Syntax

VOIDSetType(SHORT s);

SHORTGetType(VOID);

Set Parameters

Type | Example | Description
SHORT | s | An integer with one of the values shown in Remarks.

Remarks

The following are valid data types.

Constant | Description
dbBigInt | Big Integer
dbBinary | Binary
dbBoolean | Boolean
dbByte | Byte
dbChar | Char
dbCurrency | Currency
dbDate | Date/Time
dbDecimal | Decimal
dbDouble | Double
dbFloat | Float
dbGUID | GUID
dbInteger | Integer
dbLong | Long
dbLongBinary | Long Binary (OLE Object)
dbMemo | Memo
dbNumeric | Numeric
dbSingle | Single
dbText | Text
dbTime | Time
dbTimeStamp | Time Stamp
dbVarBinary | VarBinary


OrdinalPosition Property (dbDAO)

CdbField::SetOrdinalPosition, GetOrdinalPosition Property

Sets or returns the relative position of a CdbField object within a CdbFields collection.

Syntax

VOIDSetOrdinalPosition(SHORT s);

SHORTGetOrdinalPosition(VOID);

Set Parameters

Type | Example | Description
SHORT | s | A Short that specifies the numeric order of fields.


AllowZeroLength Property (dbDAO)

CdbField::SetAllowZeroLength, GetAllowZeroLength Property

Sets or returns a Boolean value that indicates whether a zero-length string ("") is a valid setting for the Value property of the CdbField object with a Text or Memo data type.

Syntax

VOIDSetAllowZeroLength(BOOL b);

BOOLGetAllowZeroLength(VOID);

Set Parameters

Type | Example | Description
BOOL | b | A Boolean that is TRUE if the Field object accepts a zero-length string as its Value property.


Name Property (dbDAO)

CdbField::SetName, GetName Property

Sets or returns a user-defined name for a CdbField object. For an object not appended to a collection, this property is read/write.

Settings and Return Values

The setting or return value is a CString that specifies a name. The name must start with a letter. The maximum number of characters 64. It can include numbers and underscore characters but can't include punctuation or spaces. See details in the core topic Remarks.

Syntax

VOIDSetName(LPCTSTR pstr);

CStringGetName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains the name of the field.


ValidationText Property (dbDAO)

CdbField::SetValidationText, GetValidationText Property

Sets or returns a value that specifies the text of a message. Your application displays this message if the value of a CdbField object doesn't satisfy the validation rule specified by the ValidationRule property setting (Microsoft Jet workspaces only).

Syntax

VOIDSetValidationText(LPCTSTR pstr);

CStringGetValidationText(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains the text message.


SourceTable Property (dbDAO)

CdbField::GetSourceTable Property

Returns a CString value that indicates the name of the table that is the original source of the data for a CdbField object.

Syntax

CStringGetSourceTable(VOID);


ValidationRule Property (dbDAO)

CdbField::SetValidationRule, GetValidationRule Property

Syntax

VOIDSetValidationRule(LPCTSTR pstr);

CStringGetValidationRule(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to string that contains a comparison in the form of an SQL WHERE clause without the WHERE reserved word.


VisibleValue Property (dbDAO)

CdbField::GetVisibleValue Property

Returns a value currently in the database that is newer than the OriginalValue property as determined by a batch update conflict (ODBCDirect workspaces only).

Syntax

COleVariantGetVisibleValue(VOID);

Remarks

This property contains the value of the field that is currently in the database on the server. During an optimistic batch update, a collision may occur where a second client modified the same field and record in between the time the first client retrieved the data and the first client's update attempt. When this happens, the value that the second client set will be accessible through this property.


GetChunk Method (dbDAO)

CdbField::GetChunk Method

Returns all or a portion of the contents of a Memo or Long Binary (OLE Object) Field object in the Fields collection of a Recordset object.

Syntax

COleVariantGetChunk(LONG lOffset, LONG lBytes);

Parameters

Type | Example | Description
LONG | lOffset | A numeric expression that is the number of bytes to skip before copying begins.
LONG | lBytes | A numeric expression that is the number of bytes you want to return.

Remarks

GetChunk returns COleVariant whose type is set to the type of the accessed field.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRecordset      rs;
CdbField         fld;
COleVariant      vVal;
...                           // Initialize recordset, etc.
fld = rs.Fields[0];            // Get a field. (Assume it's a 35-byte long string)
vVal = fld.GetChunk(5L, 25L);     // Skip 5 bytes, get the next 25 bytes.


ValidateOnSet Property (dbDAO)

CdbField::SetValidateOnSet, GetValidateOnSet Property

Sets or returns a Boolean value that specifies whether the value of the CdbField object is immediately validated against the object's ValidationRule property when the object's Value property is set (Microsoft Jet workspaces only).

Syntax

VOIDSetValidateOnSet(BOOL b);

BOOLGetValidateOnSet(VOID);

Set Parameters

Type | Example | Description
BOOL | b | A Boolean. TRUEthe validation rule is checked when you set the object's Value property. FALSEthe validation rule is checked when the record is updated.


Required Property (dbDAO)

CdbField::SetRequired, GetRequired Property

Sets or returns a Boolean value that indicates whether a CdbField object requires a non-Null value.

Syntax

VOIDSetRequired(BOOL b);

BOOLGetRequired(VOID);

Set Parameters

Type | Example | Description
BOOL | b | A Boolean that is TRUE if a field can't contain a Null value.


FieldSize Property (dbDAO)

CdbField::GetFieldSize Property

Returns the number of bytes used in the database (rather than in memory) of a Memo or Long Binary Field object in the Fields collection of a Recordset object.

Syntax

LONGGetFieldSize(VOID);

Remarks

To determine the size of a Field object other than Memo and Long Binary types, use the Size property.

In an ODBCDirect workspace, the FieldSize property is not available in the following situations:

  • If the database server or ODBC driver does not support server-side cursors. (For example, Microsoft SQL Server version 4.21 does not support server-side cursors, so the FieldSize property is not available.)

  • If you are using the ODBC cursor library (that is, the DefaultCursorDriver property is set to dbUseODBC, or to dbUseDefault when the server does not support server-side cursors).

  • If you are using a cursorless query (that is, the DefaultCursorDriver property is set to dbUseNoCursor).


Attributes Property (dbDAO)

CdbField::SetAttributes, GetAttributes Property

Sets or returns a value that indicates one or more characteristics of a CdbField object.

Syntax

VOIDSetAttributes(LONG l);

LONGGetAttributes(VOID);

Set Parameters

Type | Example | Description
LONG | l | A Long with one or more of the values listed in Remarks.

Remarks

The valid values are the following:

Constant | Description
dbAutoIncrField | The field value for new records is automatically incremented to a unique Long integer that can't be changed (in a Microsoft Jet workspace, supported only for Microsoft Jet database(.mdb) tables).
dbDescending | The field is sorted in descending (Z to A or 100 to 0) order; this option applies only to a Field object in a Fields collection of an Index object. If you omit this constant, the field is sorted in ascending (A to Z or 0 to 100) order. This is the default value for Index and TableDef fields (Microsoft Jet workspaces only).
dbFixedField | The field size is fixed (default for Numeric fields).
dbHyperlinkField | The field contains hyperlink information (Memo fields only).
dbSystemField | The field stores replication information for replicas; you can't delete this type of field (Microsoft Jet workspaces only).
dbUpdatableField | The field value can be changed.
dbVariableField | The field size is variable (Text fields only).


Value Property (dbDAO)

CdbField::SetValue, GetValue Property

Sets or returns the value of a CdbField object.

Syntax

VOIDSetValue(LPVARIANT pv);

COleVariantGetValue(VOID);

Set Parameters

Type | Example | Description
LPVARIANT | pv | A pointer to a COleVariant that contains the value to be inserted into the CdbField object.

Remarks

See also CdbRecordset::SetField and CdbRecordset::GetField.


DataUpdatable Property (dbDAO)

CdbField::GetDataUpdatable Property

Returns a value that indicates whether you can change the CdbField object.

The return value is a Boolean that is TRUE if the object can be changed or updated. (Snapshot- and forward-only–type Recordset objects always return FALSE.)

Syntax

BOOLGetDataUpdatable(VOID);


SourceField Property (dbDAO)

CdbField::GetSourceField Property

Returns a CString value that contains the name of the field that is the original source of the data for a CdbField object.

Syntax

CStringGetSourceField(VOID);


Size Property (dbDAO)

CdbField::SetSize, GetSize Property

Sets or returns a value that indicates the maximum size, in bytes, of a CdbField object.

Settings and Return Values

The setting or return value is a constant that indicates the maximum size of a Field object. The setting depends on the Type property setting of the Field object, as discussed under the core topic Remarks.

Syntax

VOIDSetSize(LONG l);

LONGGetSize(VOID);

Set Parameters

Type | Example | Description
LONG | l | A Long that specifies the length of the field.


CollectionIndex Property (dbDAO)

CdbField::GetCollectionIndex Property

Syntax

SHORT GetCollectionIndex(VOID);

Remarks


CacheSize Property (dbDAO)

CdbQueryDef::SetCacheSize, GetCacheSize Property

Sets or returns the number of records retrieved from an ODBC data source that will be cached locally. The setting or return value must be between 5 and 1200, but not greater than available memory will allow. A setting of 0 turns off caching.

Syntax

VOIDSetCacheSize(LONG l);

LONGGetCacheSize(VOID);

Set Parameters

Type | Example | Description
LONG | l | A Long specifying the number of records that will be cached.

Remarks

Data caching improves performance if you use Recordset objects to retrieve data from a remote server. When users request data, the Microsoft Jet database engine checks the cache for the requested data first rather than retrieving it from the server. The cache only saves data that comes from an ODBC data source.


StillExecuting Property (dbDAO)

CdbQueryDef::GetStillExecuting Property

Returns a Boolean value indicating whether or not an asynchronous operation (that is, a method called with the dbRunAsync option) has finished executing (ODBCDirect workspaces only). The return value is TRUE if the query is still executing, and FALSE if the query has completed.

Syntax

BOOLGetStillExecuting(VOID);

Remarks

Use the StillExecuting property to determine if the most recently called asynchronous Execute method (that is, a method executed with the dbRunAsync option) is complete. While the StillExecuting property is TRUE, any returned object cannot be accessed.


ReturnsRecords Property (dbDAO)

CdbQueryDef::SetReturnsRecords, GetReturnsRecords Property

Sets or returns a Boolean value that indicates whether an SQL pass-through query to an external database returns records.

Syntax

VOIDSetReturnsRecords(BOOL b);

BOOLGetReturnsRecords(VOID);

Set Parameters

Type | Example | Description
BOOL | b | A Boolean that is set to TRUE if a pass-through query returns records.

Remarks

You must set the Connect property before you set the ReturnsRecords property.


OpenRecordset Method (dbDAO)

CdbQueryDef::OpenRecordset Method

Creates a new Recordset object and appends it to the Recordsets collection.

Syntax

CdbRecordsetOpenRecordset(LONG lType=-1,

LONG lOption=-1,

LONG lLockType=-1);

Parameters

Type | Example | Description
LONG | lType | Optional. A constant that indicates the type of Recordset to open, as specified in Settings in the core topic.
LONG | lOption | Optional. A combination of constants that specify characteristics of the new Recordset, as listed in Settings in the core topic.
LONG | lLockType | Optional. A constant that determines the locking for the Recordset, as specified in Settings in the core topic.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbQueryDef      qd;
CdbRecordset      rst;
...               // Initialize qd, etc.
rst = qd.OpenRecordset( dbOpenDynaset, dbDenyWrite, dbPessimistic);


Execute Method (dbDAO)

CdbQueryDef::Execute Method

Runs an action query or executes an SQL statement on a specified Connection or Database object.

Syntax

VOIDExecute(LONG lOption=-1);

Parameters

Type | Example | Description
LONG | lOption | Optional. A constant or combination of constants that determines the data integrity characteristics of the query, as specified in Settings.

Settings

You can use the following constants for options.

Constant | Description
dbDenyWrite | Denies write permission to other users (Microsoft Jet workspaces only).
dbInconsistent | (Default) Executes inconsistent updates (Microsoft Jet workspaces only).
dbConsistent | Executes consistent updates (Microsoft Jet workspaces only).
dbSQLPassThrough | Executes an SQL pass-through query. Setting this option passes the SQL statement to an ODBC database for processing (Microsoft Jet workspaces only).
dbFailOnError | Rolls back updates if an error occurs (Microsoft Jet workspaces only).
dbSeeChanges | Generates a run-time error if another user is changing data you are editing (Microsoft Jet workspaces only).
dbRunAsync | Executes the query asynchronously (ODBCDirect Connection and QueryDef objects only).
dbExecDirect | Executes the statement without first calling SQLPrepare ODBC API function (ODBCDirect Connection and QueryDef objects only).

Note that the constants dbConsistent and dbInconsistent are mutually exclusive. You can use one or the other, but not both.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbQueryDef       qd;
CdbConnection   conn;
LPCTSTR    lpctsrSQL =
            _T("SELECT SALARY FROM EMPLOYEES ")
            _T("WHERE LASTNAME = 'SMITH'");
...
qd = conn.CreateQueryDef(_T("SALARYDEF"), lpctsrSQL);
qd.Execute(dbFailOnError);


CreateProperty Method (dbDAO)

CdbQueryDef::CreateProperty Method

Creates a new user-defined Property object.

Syntax

CdbPropertyCreateProperty(LPCTSTR pstrName=NULL,

LONG lType=-1,

LPVARIANT pvValue=NULL,

BOOL bDDL=FALSE);

Parameters

Type | Example | Description
LPCTSTR | pstrName | Optional. A pointer to a string that contains the name of the new property.
LONG | lType | Optional. The type of the new property. Its value may be one of those listed under "Types" in the core topic.
LPVARIANT | pvValue | Optional. A pointer to a variant containing the initial property value. See the Value property for details.
BOOL | bDDL | Optional. A Boolean indicating whether or not the created Property object is a Data Definition Language object. If TRUE, the created Property object can't be changed or deleted unless the user has dbSecWriteDef permission. The default is FALSE.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbQueryDef      qd;
CdbProperty      prop;
COleVariant      vVal(FALSE, VT_BOOL);
...               // Initialize the qd, etc.
...               // Create a property in the querydef
prop = qd.CreateProperty(_T("Required"), dbBoolean, &vVal, FALSE);
qd.Properties.Append( prop );


MaxRecords Property (dbDAO)

CdbQueryDef::SetMaxRecords, GetMaxRecords Property

Sets or returns the maximum number of records to return from a query. The default value is 0, indicating no limit on the number of records returned.

Syntax

VOIDSetMaxRecords(LONG l);

LONGGetMaxRecords(VOID);

Set Parameters

Type | Example | Description
LONG | l | A Long specifying the maximum number of records to return.

Remarks

Once the number of rows specified by MaxRecords is returned to your application in a Recordset, the query processor will stop returning additional records even if more records would qualify for inclusion in the Recordset. This property is useful in situations where limited client resources prohibit management of large numbers of records.


Cancel Method (dbDAO)

CdbQueryDef::Cancel Method

Cancels execution of a pending asynchronous (that is, the method was invoked with the dbRunAsync option) Execute method call (ODBCDirect workspaces only). Cancel will return a run-time error if dbRunAsync was not used in the method you're trying to terminate.

Syntax

VOIDCancel(VOID);

Usage

#include <afxole.h>
#include <dbdao.h>

CdbQueryDef       qd;
CdbConnection   conn;
LPCTSTR    lpctsrSQL =
            _T("SELECT SALARY FROM EMPLOYEES ")
            _T("WHERE LASTNAME = 'SMITH'");
...
qd = conn.CreateQueryDef(_T("SALARYDEF"), lpctsrSQL);
qd.Execute(dbRunAsync);
...
if (Error) qd.Cancel();


Name Property (dbDAO)

CdbQueryDef::SetName, GetName Property

Sets or returns a user-defined name for a CdbQueryDef object.

Settings and Return Values

The setting or return value is a string that specifies a name. The name must start with a letter. The maximum number of characters is 64. It can include numbers and underscore characters but can't include punctuation or spaces.

Syntax

VOIDSetName(LPCTSTR pstr);

CStringGetName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that that specifies a name.


Type Property (dbDAO)

CdbQueryDef::GetType Property

Returns a value that indicates the operational type of a CdbQueryDef object.

Syntax

SHORTGetType(VOID);

Remarks

Valid return values are the following:

Constant | Query type
dbQAction | Action
dbQAppend | Append
dbQCompound | Compound
dbQCrosstab | Crosstab
dbQDDL | Data-definition
dbQDelete | Delete
dbQMakeTable | Make-table
dbQProcedure | Procedure (ODBCDirect workspaces only)
dbQSelect | Select
dbQSetOperation | Union
dbQSPTBulk | Used with dbQSQLPassThrough to specify a query that doesn't return records (Microsoft Jet workspaces only)
dbQSQLPassThrough | Pass-through (Microsoft Jet workspaces only)
dbQUpdate | Update


ODBCTimeout Property (dbDAO)

CdbQueryDef::SetODBCTimeout, GetODBCTimeout Property

The setting or return value is a number representing the number of seconds to wait before a timeout error occurs when a QueryDef is executed on an ODBC database.

Syntax

VOIDSetODBCTimeout(SHORT s);

SHORTGetODBCTimeout(VOID);

Set Parameters

Type | Example | Description
SHORT | s | A Short that contains number of seconds to wait before a timeout error occurs. When the ODBCTimeout property is set to 0, no timeout error occurs. When the ODBCTimeout property is set to -1, the timeout defaults to the current setting of the QueryTimeout property of the CdbConnection or CdbDatabase object that contains the QueryDef.


CdbQueryDef Constructor (dbDAO)

CdbQueryDef Constructor

Syntax Summary

CONSTRUCTORCdbQueryDef(VOID);

CONSTRUCTORCdbQueryDef(const CdbQueryDef &);

CONSTRUCTORCdbQueryDef(DAOQueryDef *pqd,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax/Parameters/Remarks

CONSTRUCTORCdbQueryDef(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax/Parameters/Remarks

CONSTRUCTORCdbQueryDef(const CdbQueryDef &);

Type | Description
const CdbQueryDef & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax/Parameters/Remarks

CONSTRUCTORCdbQueryDef(DAOQueryDef *pqd,

BOOL bAddRef=FALSE);

Type | Example | Description
DAOQueryDef * | pqd | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.

Note In DAO the default collection for the CdbQueryDef object is Parameters. However, in the DAO SDK the default collection for the CdbQueryDef object is Fields. The default collection is accessed by applying the subscript ([ ]) operator to the CdbQueryDef object.


Updatable Property (dbDAO)

CdbQueryDef::GetUpdatable Property

Returns a Boolean value that indicates whether you can change a CdbQueryDef object.

The return value is TRUE if the object can be changed or updated.

Syntax

BOOLGetUpdatable(VOID);


Connect Property (dbDAO)

CdbQueryDef::SetConnect, GetConnect Property

Sets or returns a value that provides information about the source of an open connection, an open database, a database used in a pass-through query, or a linked table.

Syntax

VOIDSetConnect(LPCTSTR pstr);

CStringGetConnect(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains connection information.

Remarks

For appended CdbQueryDef objects this property is read-only.


RecordsAffected Property (dbDAO)

CdbQueryDef::GetRecordsAffected Property

Returns the number of records affected by the most recently invoked Execute method.

The return value is a Long from 0 to the number of records affected.

Syntax

LONGGetRecordsAffected(VOID);


DateCreated Property (dbDAO)

CdbQueryDef::GetDateCreated Property, GetLastUpdated Property

GetDateCreated returns the date and time that a CdbQueryDef object was created (Microsoft Jet workspaces only).

GetLastUpdated returns the date and time of the most recent change made to a CdbQueryDef object (Microsoft Jet workspaces only).

Syntax

COleDateTimeGetDateCreated(VOID);

COleDateTimeGetLastUpdated(VOID);


SQL Property (dbDAO)

CdbQueryDef::SetSQL, GetSQL Property

Sets or returns the SQL statement that defines the query executed by a CdbQueryDef object.

Syntax

VOIDSetSQL(LPCTSTR pstr);

CStringGetSQL(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains an SQL statement.


Prepare Property (dbDAO)

CdbQueryDef::SetPrepare, GetPrepare Property

Sets or returns a value that indicates whether the query should be prepared on the server as a temporary stored procedure, using the ODBC SQLPrepare API function, prior to execution, or just executed using the ODBC SQLExecDirect API function (ODBCDirect workspaces only).

Syntax

VOIDSetPrepare(LPVARIANT pv);

COleVariantGetPrepare(VOID);

Set Parameters

Type | Example | Description
LPVARIANT | pv | A pointer to a variant with one of the values shown below.

The setting or return value can be one of the following constants:

Constant | Description
dbQPrepare | (Default) The statement is prepared (that is, the ODBC SQLPrepare API is called).
dbQUnprepare | The statement is not prepared (that is, the ODBC SQLExecDirect API is called).


RecordCount Property (dbDAO)

CdbTableDef::GetRecordCount Property

Returns the number of records accessed in a Recordset object, or the total number of records in a table-type Recordset or TableDef object.

Syntax

LONGGetRecordCount(VOID);

Remarks

Use the RecordCount property to find out how many records in a Recordset or TableDef object have been accessed. The RecordCount property doesn't indicate how many records are contained in a dynaset-, snapshot-, or forward-only–type Recordset object until all records have been accessed. Once the last record has been accessed, the RecordCount property indicates the total number of undeleted records in the Recordset or TableDef object. To force the last record to be accessed, use the MoveLast method on the Recordset object. You can also use an SQL Count function to determine the approximate number of records your query will return.

Note Using the MoveLast method to populate a newly opened Recordset negatively impacts performance. Unless it is necessary to have an accurate record count as soon as you open a Recordset, it's better to wait until you populate the Recordset with other portions of code before checking the RecordCount property.


OpenRecordset Method (dbDAO)

CdbTableDef::OpenRecordset Method

Creates a new Recordset object and appends it to the Recordsets collection.

Syntax

CdbRecordsetOpenRecordset(LONG lType=-1,

LONG lOption=-1);

Parameters

Type | Example | Description
LONG | lType | Optional. A constant that indicates the type of Recordset to open. (See Settings in core topic).
LONG | lOption | Optional. A combination of constants that specify characteristics of the new Recordset. (See Settings in core topic).

Usage

#include <afxole.h>
#include <dbdao.h>

CdbDBEnghine      dben;
CdbDatabase      dbs;
CdbRecordset      rst;
CdbTableDef      td;
CdbField         fld;
   // Initialize the TableDef.
dbs = dben.OpenDatabase(...);
td = dbs.CreateTableDef(...);
fld = td.CreateField(...);
td.Fields.Append(fld);
dbs.TableDefs.Append(td);
   // Open a recordset based on the TableDef.
rst = td.OpenRecordset( dbOpenTable, dbAppendOnly );


CreateProperty Method (dbDAO)

CdbTableDef::CreateProperty Method

Creates a new user-defined Property object.

Syntax

CdbPropertyCreateProperty(LPCTSTR pstrName=NULL,

LONG lType=-1,

LPVARIANT pvValue=NULL,

BOOL bDDL=FALSE);

Parameters

Type | Example | Description
LPCTSTR | pstrName =NULL | Optional. A pointer to a string that contains the name of the new property.
LONG | lType | Optional. The type of the new property. Its value may be one of those listed under "Types" in the core topic.
LPVARIANT | pvValue =NULL | Optional. A pointer to a variant containing the initial property value. See the Value property for details.
BOOL | bDDL =FALSE | Optional. A Boolean indicating whether or not the created Property object is a Data Definition Language object. If TRUE, the created Property object can't be changed or deleted unless the user has dbSecWriteDef permission. The default is FALSE.

Usage

#include <afxole.h>
#include <dbdao.h>
...
CdbTableDef      td;
CdbProperty      prop;
COleVariant      vVal(FALSE, VT_BOOL);
...               // Initialize td, etc.
prop = td.CreateProperty(_T("Required"), dbBoolean, &vVal, FALSE);
td.Properties.Append( prop );


SourceTableName Property (dbDAO)

CdbTableDef::SetSourceTableName, GetSourceTableName Property

Sets or returns a value that specifies the name of a linked table or the name of a base table (Microsoft Jet workspaces only).

Settings and Return Values

The setting or return value is a string that specifies a table name. For a base table, the setting is a zero-length string ("").

Syntax

VOIDSetSourceTableName(LPCTSTR pstr);

CStringGetSourceTableName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that specifies a table name.


CdbTableDef Constructor (dbDAO)

CdbTableDef Constructor

Syntax Summary

CONSTRUCTORCdbTableDef(VOID);

CONSTRUCTORCdbTableDef(const CdbTableDef &);

CONSTRUCTORCdbTableDef(DAOTableDef *ptd,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax / Parameters / Remarks

CONSTRUCTORCdbTableDef(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax / Parameters / Remarks

CONSTRUCTORCdbTableDef(const CdbTableDef &);

Type | Description
const CdbTableDef & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax / Parameters / Remarks

CONSTRUCTORCdbTableDef(DAOTableDef *ptd,

BOOL bAddRef=FALSE);

Type | Example | Description
DAOTableDef * | ptd | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


CreateIndex Method (dbDAO)

CdbTableDef::CreateIndex Method

Creates a new Index object (Microsoft Jet workspaces only).

Syntax

CdbIndexCreateIndex(LPCTSTR pstrName=NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName=NULL | Optional. A pointer to a string that uniquely names the new Index object. See the Name property for details on valid Index names.

Remarks

To remove an Index object from a collection, use the Delete method on the collection.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbIndex      idx;
CdbTableDef   td;
...                           // Initialize td, etc.
idx = td.CreateIndex(   _T("CarPartsIdx"));


Attributes Property (dbDAO)

CdbTableDef::SetAttributes, GetAttributes Property

Sets or returns a value that indicates one or more characteristics of a table represented by the CdbTableDef object.

Syntax

VOIDSetAttributes(LONG l);

LONGGetAttributes(VOID);

Set Parameters

Type | Example | Description
LONG | l | A Long containing one or a combination of the values listed in Remarks.

Remarks

Valid values can be a combination of the following:

Constant | Description
dbAttachExclusive | For databases that use the Microsoft Jet database engine, the table is a linked table opened for exclusive use. You can set this constant on an appended TableDef object for a local table, but not on a remote table.
dbAttachSavePWD | For databases that use the Microsoft Jet database engine, the user ID and password for the remotely linked table are saved with the connection information. You can set this constant on an appended TableDef object for a remote table, but not on a local table.
dbSystemObject | The table is a system table provided by the Microsoft Jet database engine. You can set this constant on an appended TableDef object.
dbHiddenObject | The table is a hidden table provided by the Microsoft Jet database engine. You can set this constant on an appended TableDef object.
dbAttachedTable | The table is a linked table from a non-ODBC data source such as a Microsoft Jet or Paradox database (read-only).
dbAttachedODBC | The table is a linked table from an ODBC data source, such as Microsoft SQL Server (read-only).


Connect Property (dbDAO)

CdbTableDef::SetConnect, GetConnect Property

Sets or returns a value that provides information about the source of an open connection, an open database, a database used in a pass-through query, or a linked table.

Syntax

VOIDSetConnect(LPCTSTR pstr);

CStringGetConnect(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string composed of a database type specifier and zero or more parameters separated by semicolons. The Connect property passes additional information to ODBC and certain ISAM drivers as needed.

Remarks

For a TableDef object that represents a linked table, the Connect property setting consists of one or two parts (a database type specifier and a path to the database), each of which ends with a semicolon.


IniPath Property (dbDAO)

CdbTableDef::GetDateCreated Property, GetLastUpdated Property

GetDateCreated returns the date and time that a CdbTableDef object was created (Microsoft Jet workspaces only).

GetLastUpdated returns the date and time of the most recent change made to a CdbTableDef object (Microsoft Jet workspaces only).

Syntax

COleDateTimeGetDateCreated(VOID);

COleDateTimeGetLastUpdated(VOID);


Name Property (dbDAO)

CdbTableDef::SetName, GetName Property

Sets or returns a user-defined name for a CdbTableDef object.

Settings and Return Values

The setting or return value is a string that specifies a name. The name must start with a letter. The maximum number of characters is 64. It can include numbers and underscore characters but can't include punctuation or spaces.

Syntax

VOIDSetName(LPCTSTR pstr);

CStringGetName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that that specifies a name.


ReplicaFilter Property (dbDAO)

CdbTableDef::SetReplicaFilter, GetReplicaFilter Property

Sets or returns a value on a TableDef object within a partial replica that indicates which subset of records is replicated to that table from a full replica. (Microsoft Jet databases only.)

Syntax

VOIDSetReplicaFilter(LPVARIANT pv);

COleVariantGetReplicaFilter(VOID);

Set Parameters

Type | Example | Description
LPVARIANT | pv | A pointer to a variant whose value is a string or Boolean that indicates which subset of records is replicated as described in Settings.

Settings

Value | Description
A string | A criteria that a record in the partial replica table must satisfy in order to be replicated from the full replica. This property is similar to an SQL WHERE clause (without the reserved word WHERE), but you cannot specify subqueries, aggregate functions (such as Count), or user-defined functions within the criteria.
TRUE | Replicates all records.
FALSE | (Default) Doesn't replicate any records.


Updatable Property (dbDAO)

CdbTableDef::GetUpdatable Property

Returns a Boolean value that indicates whether you can change a CdbQueryDef object.

The return value is TRUE if the object can be changed or updated.

Syntax

BOOLGetUpdatable(VOID);


ValidationText Property (dbDAO)

CdbTableDef::SetValidationText, GetValidationText Property

Sets or returns a value that specifies the text of the message that your application displays if the value of a CdbField object associated with the CdbTableDef object doesn't satisfy the validation rule specified by the ValidationRule property setting (Microsoft Jet workspaces only).

Syntax

VOIDSetValidationText(LPCTSTR pstr);

CStringGetValidationText(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains the validation text.


ConflictTable Property (dbDAO)

CdbTableDef::GetConflictTable Property

Returns the name of a conflict table containing the database records that conflicted during the synchronization of two replicas (Microsoft Jet workspaces only).

The return value is a CString that is a zero-length string if there is no conflict table or the database isn't a replica.

Syntax

CStringGetConflictTable(VOID);

Remarks

If two users at two separate replicas each make a change to the same record in the database, the changes made by one user will fail to be applied to the other replica. Consequently, the user with the failed change must resolve the conflicts.

All conflict tables are named table_conflict, where table is the original name of the table, truncated to the maximum table name length.


ValidationRule Property (dbDAO)

CdbTableDef::SetValidationRule, GetValidationRule Property

Sets or returns a value that validates the data in a field as it's changed or added to a table (Microsoft Jet workspaces only).

Syntax

VOIDSetValidationRule(LPCTSTR pstr);

CStringGetValidationRule(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains a comparison in the form of an SQL WHERE clause without the WHERE reserved word.


RefreshLink Method (dbDAO)

CdbTableDef::RefreshLink Method

Updates the connection information for a linked table (Microsoft Jet workspaces only).

Syntax

VOIDRefreshLink(VOID);

Remarks

To change the connection information for a linked table, reset the Connect property of the corresponding TableDef object and then use the RefreshLink method to update the information. Using the RefreshLink method doesn't change the linked table's properties and Relation objects.

For this connection information to exist in all collections associated with the TableDef object that represents the linked table, you must use the Refresh method on each collection.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbTableDef      td;
...
td.SetConnect(_T("Excel 8.0;drive:\path\filename.xls"));
td.RefreshLink();


CreateField Method (dbDAO)

CdbTableDef::CreateField Method

Creates a new Field object (Microsoft Jet workspaces only).

Syntax

CdbFieldCreateField(LPCTSTR pstrName=NULL,

LONG lType=-1,

LONG lSize=-1);

Parameters

Type | Example | Description
LPCTSTR | pstrName = NULL | Optional. A pointer to a string that uniquely names the new Field object. See the Name property for details on valid Field names.
LONG | lType=-1 | Optional. An integer that determines the data type of the new Field object. See the Type property for valid data types.
LONG | lSize=-1 | Optional. An integer that indicates the maximum size, in bytes, of a Field object that contains text. See the Size property for valid size values. This argument is ignored for numeric and fixed-width fields.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbTableDef   td;
...
td.CreateField(_T("CarModel"), dbText, 30);


IgnoreNulls Property (dbDAO)

CdbIndex::SetIgnoreNulls, GetIgnoreNulls Property

Sets or returns a Boolean value that indicates whether records that have Null values in their index fields have index entries (Microsoft Jet workspaces only).

Syntax

VOIDSetIgnoreNulls(BOOL b);

BOOLGetIgnoreNulls(VOID);

Set Parameters

Type | Example | Description
BOOL | b | A Boolean that is TRUE if the fields with Null values don't have an index entry.


CreateField Method (dbDAO)

CdbIndex::CreateField Method

Creates a new Field object (Microsoft Jet workspaces only).

Syntax

CdbFieldCreateField(LPCTSTR pstrName=NULL,

LONG lType=-1,

LONG lSize=-1);

Parameters

Type | Example | Description
LPCTSTR | pstrName= NULL | Optional. A pointer to a string that uniquely names the new Field object. See the Name property for details on valid Field names.
LONG | lType=-1 | Optional. An integer that determines the data type of the new Field object. See the Type property for valid data types.
LONG | lSize=-1 | Optional. An integer that indicates the maximum size, in bytes, of a Field object that contains text. See the Size property for valid size values. This argument is ignored for numeric and fixed-width fields.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbIndex   idx;
CdbField   fld;
...
fld = idx.CreateField(_T("CarModel"), dbText, 30);
idx.Fields.Append( fld );


Primary Property (dbDAO)

CdbIndex::SetPrimary, GetPrimary Property

Sets or returns a Boolean value that indicates whether an Index object represents a primary index for a table (Microsoft Jet workspaces only).

Syntax

VOIDSetPrimary(BOOL b);

BOOLGetPrimary(VOID);

Set Parameters

Type | Example | Description
BOOL | b | A Boolean that is TRUE if the Index object represents a primary index.


CreateProperty Method (dbDAO)

CdbIndex::CreateProperty Method

Creates a new user-defined Property object.

Syntax

CdbPropertyCreateProperty(LPCTSTR pstrName=NULL,

LONG lType=-1,

LPVARIANT pvValue=NULL,

BOOL bDDL=FALSE);

Parameters

Type | Example | Description
LPCTSTR | pstrName =NULL | Optional. A pointer to a string that contains the name of the new Property.
LONG | lType | Optional. The type of the new Property. Its value may be one of those listed under "Types" in the core topic.
LPVARIANT | pvValue =NULL | Optional. A Variant variable containing the initial property value. See the Value property for details.
BOOL | bDDL =FALSE | Optional. A Boolean variable indicating whether or not the Property is a DDL object. The default is FALSE. If the bDDL is TRUE, this Property object can't be changed or deleted unless the user has dbSecWriteDef permission.

Usage

#include <afxole.h>
#include <dbdao.h>
...
CdbIndex         idx;
CdbProperty      prop;
COleVariant      vVal(FALSE, VT_BOOL);
   // Initialize index, etc.
prop = idx.CreateProperty(_T("Required"), dbBoolean, &vVal, FALSE);
idx.Properties.Append( prop );


Clustered Property (dbDAO)

CdbIndex::SetClustered, GetClustered Property

Sets or returns a Boolean value that indicates whether an CdbIndex object represents a clustered index for a table (Microsoft Jet workspaces only).

Syntax

VOIDSetClustered(BOOL b);

BOOLGetClustered(VOID);

Set Parameters

Type | Example | Description
BOOL | b | A Boolean that is set to TRUE if the Index object represents a clustered index.


Name Property (dbDAO)

CdbIndex::SetName, GetName Property

Sets or returns a user-defined name for a CdbIndex object.

Settings and Return Values

The setting or return value is a string that specifies a name. The name must start with a letter. The maximum number of characters is 64. It can include numbers and underscore characters but can't include punctuation or spaces.

Syntax

VOIDSetName(LPCTSTR pstr);

CStringGetName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A string that contains a name.

Usage

CdbDBEngine      dben;
CdbIndex         idx;
CdbDatabase      dbs;
CdbTableDef      tdf;
CdbRecordset      rst;
   // Get your database.
dbs = dben.OpenDatabase(...);
   // Get your TableDef from the database.
tdf = dbs.TableDefs[_T("TableDefName")];
   // Get the first Index from the TableDef.
idx = tdf.Indexes[0L];
rst = dbs.OpenRecordset(...,dbOpenTable);
rst.SetIndex((LPCTSTR)idx.GetName());
rst.Seek(...);
...


Required Property (dbDAO)

CdbIndex::SetRequired, GetRequired Property

Sets or returns a Boolean value that indicates whether all the fields in a CdbIndex object must have a value.

Syntax

VOIDSetRequired(BOOL b);

BOOLGetRequired(VOID);

Set Parameters

Type | Example | Description
BOOL | b | A Boolean set to TRUE if all fields are required to contain non-Null values.


Unique Property (dbDAO)

CdbIndex::SetUnique, GetUnique Property

Sets or returns a Boolean value that indicates whether an CdbIndex object represents a unique (key) index for a table (Microsoft Jet workspaces only).

Syntax

VOIDSetUnique(BOOL b);

BOOLGetUnique(VOID);

Set Parameters

Type | Example | Description
BOOL | b | A Boolean set to TRUE if the Index object represents a unique index.


CdbIndex Constructor (dbDAO)

CdbIndex Constructor

Syntax Summary

CONSTRUCTORCdbIndex(VOID);

CONSTRUCTORCdbIndex(const CdbIndex &);

CONSTRUCTORCdbIndex(DAOIndex *pidx,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax / Parameters / Remarks

CONSTRUCTORCdbIndex(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax / Parameters / Remarks

CONSTRUCTORCdbIndex(const CdbIndex &);

Type | Description
const CdbIndex & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax / Parameters / Remarks

CONSTRUCTORCdbIndex(DAOIndex *pidx,

BOOL bAddRef=FALSE);

Type | Example | Description
DAOIndex * | pidx | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


DistinctCount Property (dbDAO)

CdbIndex::GetDistinctCount Property

Returns a value that indicates the number of unique values for the CdbIndex object that are included in the associated table (Microsoft Jet workspaces only).

Syntax

LONGGetDistinctCount(VOID);

Remarks

Check the DistinctCount property to determine the number of unique values, or keys, in an index. Any key is counted only once, even though there may be multiple occurrences of that value if the index permits duplicate values. This information is useful in applications that attempt to optimize data access by evaluating index information. The number of unique values is also known as the cardinality of a CdbIndex object.


Foreign Property (dbDAO)

CdbIndex::GetForeign Property

Returns a Boolean value that indicates whether an Index object represents a foreign key in a table (Microsoft Jet workspaces only).

The return value is TRUE if the Index object represents a foreign key.

Syntax

BOOLGetForeign(VOID);

Remarks

A foreign key consists of one or more fields in a foreign table that uniquely identify all records in a primary table.

The Microsoft Jet database engine creates an Index object for the foreign table and sets the Foreign property when you create a relationship that enforces referential integrity.


CreateField Method (dbDAO)

CdbRelation::CreateField Method

Creates a new Field object (Microsoft Jet workspaces only).

Syntax

CdbFieldCreateField(LPCTSTR pstrName=NULL,

LONG lType=-1,

LONG lSize=-1);

Parameters

Type | Example | Description
LPCTSTR | pstrName= NULL | Optional. A pointer to a string that uniquely names the new Field object. See the Name property for details on valid Field names.
LONG | lType=-1 | Optional. An integer that determines the data type of the new Field object. See the Type property for valid data types.
LONG | lSize=-1 | Optional. An integer that indicates the maximum size, in bytes, of a Field object that contains text. See the Size property for valid size values. This argument is ignored for numeric and fixed-width fields.

Usage

#include <afxole.h>
#include <dbdao.h>

CdbRelation   rel;
CdbField   fld;
...
fld = rel.CreateField(_T("CarModel"), dbText, 30);


Name Property (dbDAO)

CdbRelation::SetName, GetName Property

Sets or returns a user-defined name for a CdbRelation object.

Settings and Return Values

The setting or return value is a string that specifies a name. The name must start with a letter. The maximum number of characters is 64. It can include numbers and underscore characters but can't include punctuation or spaces.

Syntax

VOIDSetName(LPCTSTR pstr);

CStringGetName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string containing a name.


Attributes Property (dbDAO)

CdbRelation::SetAttributes, GetAttributes Property

Sets or returns a value that indicates one or more characteristics of a CdbRelation object.

Syntax

VOIDSetAttributes(LONG);

LONGGetAttributes(VOID);

Set Parameters

Type | Description
LONG | A Long that contains one or more of the values described in Remarks.

Remarks

The following are valid values.

Constant | Description
dbRelationUnique | The relationship is one-to-one.
dbRelationDontEnforce | The relationship isn't enforced (no referential integrity).
dbRelationInherited | The relationship exists in a non-current database that contains the two linked tables.
dbRelationUpdateCascade | Updates will cascade.
dbRelationDeleteCascade | Deletions will cascade.


ForeignTable Property (dbDAO)

CdbRelation::SetForeignTable, GetForeignTable Property

Sets or returns the name of the foreign table in a relationship (Microsoft Jet workspaces only).

The setting or return value is a string that evaluates to the name of a table in the Database object's TableDefs collection.

Syntax

VOIDSetForeignTable(LPCTSTR pstr);

CStringGetForeignTable(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains the name of the foreign table.


Table Property (dbDAO)

CdbRelation::SetTable, GetTable Property

Indicates the name of a Relation object's primary table. This should be equal to the Name property setting of a TableDef or QueryDef object (Microsoft Jet workspaces only).

Syntax

VOIDSetTable(LPCTSTR pstr);

CStringGetTable(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains the name of a table in the TableDefs collection or query in the QueryDefs collection.


CdbRelation Constructor (dbDAO)

CdbRelation Constructor

Syntax Summary

CONSTRUCTORCdbRelation(VOID);

CONSTRUCTORCdbRelation(const CdbRelation &);

CONSTRUCTORCdbRelation(DAORelation *prl,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax / Parameters / Remarks

CONSTRUCTORCdbRelation(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax / Parameters / Remarks

CONSTRUCTORCdbRelation(const CdbRelation &);

Type | Description
const CdbRelation & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax / Parameters / Remarks

CONSTRUCTORCdbRelation(DAORelation *prl,

BOOL bAddRef=FALSE);

Type | Example | Description
DAORelation * | prl | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


PartialReplica Property (dbDAO)

CdbRelation::SetPartialReplica, GetPartialReplica Property

Sets or returns a Boolean value indicating whether the relation should be considered when populating a partial replica from a full replica. (Microsoft Jet databases only.)

Syntax

VOIDSetPartialReplica(BOOL b);

BOOLGetPartialReplica(VOID);

Set Parameters

Type | Example | Description
BOOL | b | A Boolean that indicates whether the relation should be considered when populating a partial replica. The value is TRUE when the relation should be enforced during synchronization.


CdbUser Constructor (dbDAO)

CdbUser Constructor

Syntax Summary

CONSTRUCTORCdbUser(VOID);

CONSTRUCTORCdbUser(const CdbUser &);

CONSTRUCTORCdbUser(DAOUser *pusr,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax / Parameters / Remarks

CONSTRUCTORCdbUser(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax / Parameters / Remarks

CONSTRUCTORCdbUser(const CdbUser &);

Type | Description
const CdbUser & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax / Parameters / Remarks

CONSTRUCTORCdbUser(DAOUser *pusr,

BOOL bAddRef=FALSE);

Type | Example | Description
DAOUser * | pusr | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


CreateGroup Method (dbDAO)

CdbUser::CreateGroup Method

Creates a new Group object (Microsoft Jet workspaces only).

Syntax

CdbGroupCreateGroup(LPCTSTR pstrName=NULL,

LPCTSTR pstrPID=NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new Group object. See the Name property for details on valid Group names.
LPCTSTR | pstrPID | Optional. A pointer to a string containing the PID of a group account. The identifier must contain from 4 to 20 alphanumeric characters. See the PID property for more information on valid personal identifiers.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbUser      us;
CdbGroup      grp;
...                           // Initialize the user, etc.
                                 // Create a group for the user.
   grp = us.CreateGroup(   _T("AccountsGrp"), _T("DEPT_501"));


Name Property (dbDAO)

CdbUser::SetName, GetName Property

Sets or returns a user-defined name for a CdbUser object.

Settings and Return Values

The setting or return value is a string that specifies a name. The name must start with a letter. The maximum number of characters 64. It can include numbers and underscore characters but can't include punctuation or spaces. See details in the core topic Remarks.

Syntax

VOIDSetName(LPCTSTR pstr);

CStringGetName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A string that contains a name.


PID Property (dbDAO)

CdbUser::SetPID Property

Sets the personal identifier (PID) for a user account (Microsoft Jet workspaces only).

Syntax

VOIDSetPID(LPCTSTR pstr);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to string that contains 4-20 alphanumeric characters.

Remarks

Set the PID property along with the Name and Password properties when you create a new CdbUser object.


Password Property (dbDAO)

CdbUser::SetPassword Property

Sets the password for a user account (Microsoft Jet workspaces only).

Syntax

VOIDSetPassword(LPCTSTR pstr);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains up to 14 characters and can include any characters except the ASCII character 0 (null).


NewPassword Method (dbDAO)

CdbUser::NewPassword Method

Changes the password of an existing user account or Microsoft Jet database (Microsoft Jet workspaces only).

Syntax

VOIDNewPassword(LPCTSTR pstrOld,

LPCTSTR pstrNew);

Parameters

Type | Example | Description
LPCTSTR | pstrOld | A pointer to a string that is the current setting of the Password property of the User or Microsoft Jet 3.x Database object.
LPCTSTR | pstrNew | A pointer to a string that is the new setting of the Password property of the User or Microsoft Jet 3.x Database object.

Remarks

The oldpassword and newpassword strings can be up to 14 characters long and can include any characters except the ASCII character 0 (null). To clear the password, use a zero-length string ("") for new password. Passwords are case-sensitive.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbUser   us;
...
us.NewPassword   (_T("openSesame"),  _T("enterFreely"));


CreateUser Method (dbDAO)

CdbGroup::CreateUser Method

Creates a new User object (Microsoft Jet workspaces only).

Syntax

CdbUserCreateUser(LPCTSTR pstrName=NULL,

LPCTSTR pstrPID=NULL,

LPCTSTR pstrPassword=NULL);

Parameters

Type | Example | Description
LPCTSTR | pstrName | Optional. A pointer to a string that uniquely names the new User object. See the Name property for details on valid User names.
LPCTSTR | pstrPID | Optional. A pointer to a string containing the PID of a user account. The identifier must contain from 4 to 20 alphanumeric characters. See the PID property for more information on valid personal identifiers.
LPCTSTR | pstrPassword | Optional. A pointer to a string containing the password for the new User object. The password can be up to 14 characters long and can include any characters except the ASCII character 0 (null). See the Password property for more information on valid passwords.

Usage

#include <afxole.h>
#include <dbdao.h>
CdbUser      us;
CdbGroup      grp;
...            // Initialize the group, etc.
            // Create a user in the group.
us = grp.CreateUser(   _T("Accountant"), _T("BOB_SMITH"),
                     _T("BOBSPASSWD");
grp.Users.Append( us );


Name Property (dbDAO)

CdbGroup::SetName, GetName Property

Sets or returns a user-defined name for a CdbGroup object.

Settings and Return Values

The setting or return value is a string that specifies a name. The name must start with a letter. The maximum number of characters is 20. It can include numbers and underscore characters but can't include punctuation or spaces.

Syntax

VOIDSetName(LPCTSTR pstr);

CStringGetName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains a name.


PID Property (dbDAO)

CdbGroup::SetPID Property

Sets the personal identifier (PID) for a user account (Microsoft Jet workspaces only).

Syntax

VOIDSetPID(LPCTSTR pstr);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to string that contains 4-20 alphanumeric characters.

Remarks

Set the PID property along with the Name property when you create a new CdbGroup object.


CdbGroup Constructor (dbDAO)

CdbGroup Constructor

Syntax Summary

CONSTRUCTORCdbGroup(VOID);

CONSTRUCTORCdbGroup(const CdbGroup &);

CONSTRUCTORCdbGroup(DAOGroup *pgrp,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax / Parameters / Remarks

CONSTRUCTORCdbGroup(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax / Parameters / Remarks

CONSTRUCTORCdbGroup(const CdbGroup &);

Type | Description
const CdbGroup & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax / Parameters / Remarks

CONSTRUCTORCdbGroup(DAOGroup *pgrp,

BOOL bAddRef=FALSE);

Type | Example | Description
DAOGroup * | pgrp | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Direction Property (dbDAO)

CdbParameter::SetDirection, GetDirection Property

Sets or returns a value that indicates whether the Parameter object represents an input parameter, an output parameter, both, or the return value from the procedure (ODBCDirect workspaces only).

Syntax

VOIDSetDirection(SHORT i);

SHORTGetDirection(VOID);

Set Parameters

Type | Example | Description
SHORT | i | A Short with one of the values shown in Settings.

Settings

Constant | Description
dbParamInput | (Default) Passes information to the procedure.
dbParamInputOutput | Passes information both to and from the procedure.
dbParamOutput | Returns information from the procedure as in an output parameter in SQL.
dbParamReturnValue | Passes the return value from a procedure.


CdbParameter Constructor (dbDAO)

CdbParameter Constructor

Syntax Summary

CONSTRUCTORCdbParameter(VOID);

CONSTRUCTORCdbParameter(const CdbParameter &);

CONSTRUCTORCdbParameter(DAOParameter *pprm,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax / Parameters / Remarks

CONSTRUCTORCdbParameter(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax / Parameters / Remarks

CONSTRUCTORCdbParameter(const CdbParameter &);

Type | Description
const CdbParameter & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax / Parameters / Remarks

CONSTRUCTORCdbParameter(DAOParameter *pprm,

BOOL bAddRef=FALSE);

Type | Example | Description
DAOParameter * | pprm | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Name Property (dbDAO)

CdbParameter::GetName Property

Returns a user-defined name for a CdbQueryDef object.

The return value is a CString that specifies a name. The name must start with a letter. The maximum number of characters is 64. It can include numbers and underscore characters but can't include punctuation or spaces.

Syntax

CStringGetName(VOID);


Value Property (dbDAO)

CdbParameter::SetValue, GetValue Property

Sets or returns the value of a parameter to be used in the query.

Syntax

VOIDSetValue(LPVARIANT pv);

COleVariantGetValue(VOID);

Set Parameters

Type | Example | Description
LPVARIANT | pv | A pointer to a COleVariant that contains the value to be inserted into a parameter.


Type Property (dbDAO)

CdbParameter::SetType, GetType Property

Sets or returns a value that indicates the data type of a Parameter object.

For a Microsoft Jet workspace this property is read-only, while in an ODBCDirect workspace it is read/write.

Syntax

VOIDSetType(SHORT i);

SHORTGetType(VOID);

Set Parameters

Type | Example | Description
SHORT | i | A Short with one of the values shown in Settings.

Settings

Constant | Description
dbBigInt | Big Integer
dbBinary | Binary
dbBoolean | Boolean
dbByte | Byte
dbChar | Char
dbCurrency | Currency
dbDate | Date/Time
dbDecimal | Decimal
dbDouble | Double
dbFloat | Float
dbGUID | GUID
dbInteger | Integer
dbLong | Long
dbLongBinary | Long Binary (OLE Object)
dbMemo | Memo
dbNumeric | Numeric
dbSingle | Single
dbText | Text
dbTime | Time
dbTimeStamp | Time Stamp
dbVarBinary | VarBinary


Name Property (dbDAO)

CdbDocument::GetName Property

Returns a user-defined name for a CdbDocument object.

Syntax

CStringGetName(VOID);


Permissions Property (dbDAO)

CdbDocument::SetPermissions, GetPermissions Property

Sets or returns a value that establishes the permissions for the user or group identified by the UserName property of a Container or Document object (Microsoft Jet workspaces only).

Syntax

VOIDSetPermissions(LONG l);

LONGGetPermissions(VOID);

Set Parameters

Type | Example | Description
LONG | l | A Long that contains values as listed in Remarks.

Remarks

The following are valid values.

Constant | Description
dbSecFullAccess | The user has full access to the object.
dbSecDelete | The user can delete the object.
dbSecReadSec | The user can read the object's security-related information.
dbSecWriteSec | The user can alter access permissions.
dbSecWriteOwner | The user can change the Owner property setting.


DateCreated Property (dbDAO)

CdbDocument::GetDateCreated Property, GetLastUpdated Property

GetDateCreated returns the date and time that a CdbDocumentDef object was created (Microsoft Jet workspaces only).

GetLastUpdated returns the date and time of the most recent change made to a CdbDocumentDef object (Microsoft Jet workspaces only).

Syntax

COleDateTimeGetDateCreated(VOID);

COleDateTimeGetLastUpdated(VOID);


Owner Property (dbDAO)

CdbDocument::SetOwner, GetOwner Property

Sets or returns a value that specifies the owner of the CdbDocument object (Microsoft Jet workspaces only).

Syntax

VOIDSetOwner(LPCTSTR pstr);

CStringGetOwner(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that specifies the owner of the object.


Container Property (dbDAO)

CdbDocument::GetContainer Property

Returns the name of the CdbContainer object to which a CdbDocument object belongs (Microsoft Jet workspaces only).

Syntax

CStringGetContainer(VOID);


UserName Property (dbDAO)

CdbDocument::SetUserName, GetUserName Property

Sets or returns a value that represents a user, or group of users, of a CdbDocument object.

The setting or return value is a string that evaluates to the name of a user.

Syntax

VOIDSetUserName(LPCTSTR pstr);

CStringGetUserName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains the name of a user.

Remarks

The UserName property represents a user or group of users when you manipulate the access permissions of a CdbDocument object (Microsoft Jet workspaces only).

To find or set the permissions for a particular user or group of users, first set the UserName property to the user or group name that you want to examine. Then check the Permissions property setting to determine what permissions that user or group of users has, or set the Permissions property to change the permissions.


CdbDocument Constructor (dbDAO)

CdbDocument Constructor

Syntax Summary

CONSTRUCTORCdbDocument(VOID);

CONSTRUCTORCdbDocument(const CdbDocument &);

CONSTRUCTORCdbDocument(DAODocument *pdoc,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax / Parameters / Remarks

CONSTRUCTORCdbDocument(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax / Parameters / Remarks

CONSTRUCTORCdbDocument(const CdbDocument &);

Type | Description
const CdbDocument & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax / Parameters / Remarks

CONSTRUCTORCdbDocument(DAODocument *pdoc,

BOOL bAddRef=FALSE);

Type | Example | Description
DAODocument * | pdoc | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


AllPermissions Property (dbDAO)

CdbDocument::GetAllPermissions Property

Returns all the permissions that apply to the current UserName property of the Document object, including permissions that are specific to the user as well as the permissions a user inherits from memberships in groups (Microsoft Jet workspaces only).

Syntax

LONGGetAllPermissions(VOID);

Remarks

The value(s) that may be returned are:

Constant | Description
dbSecReadDef | The user can read the table definition, including column and index information.
dbSecWriteDef | The user can modify or delete the table definition, including column and index information.
dbSecRetrieveData | The user can retrieve data from the Document object.
dbSecInsertData | The user can add records.
dbSecReplaceData | The user can modify records.
dbSecDeleteData | The user can delete records.

In addition, any Document object in a Documents collection may include the following:

Constant | Description
dbSecDeleteData | The user can delete records.
dbSecDBAdmin | The user can replicate the database and change the database password.
dbSecDBCreate | The user can create new databases. This setting is valid only on the Databases container in the workgroup information file (System.mdw).
dbSecDBExclusive | The user has exclusive access to the database.
dbSecDBOpen | The user can open the database.


CdbContainer Constructor (dbDAO)

CdbContainer Constructor

Syntax Summary

CONSTRUCTORCdbContainer(VOID);

CONSTRUCTORCdbContainer(const CdbContainer &);

CONSTRUCTORCdbContainer(DAOContainer *pctn,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax / Parameters / Remarks

CONSTRUCTORCdbContainer(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax / Parameters / Remarks

CONSTRUCTORCdbContainer(const CdbContainer &);

Type | Description
const CdbContainer & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax / Parameters / Remarks

CONSTRUCTORCdbContainer(DAOContainer *pctn,

BOOL bAddRef=FALSE);

Type | Example | Description
DAOContainer * | pctn | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Name Property (dbDAO)

CdbContainer::GetName Property

Returns a user-defined name for a CdbContainer object.

Syntax

CStringGetName(VOID);


Owner Property (dbDAO)

CdbContainer::SetOwner, GetOwner Property

Sets or returns a value that specifies the owner of the CdbDocument object (Microsoft Jet workspaces only).

Syntax

VOIDSetOwner(LPCTSTR pstr);

CStringGetOwner(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstrIndex | A pointer to a string that specifies the owner of the object.


UserName Property (dbDAO)

CdbContainer::SetUserName, GetUserName Property

Sets or returns a value that represents a user, or group of users, of a CdbContainer object.

The setting or return value is a string that evaluates to the name of a user.

Syntax

VOIDSetUserName(LPCTSTR pstr);

CStringGetUserName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstr | A pointer to a string that contains the name of a user.


Permissions Property (dbDAO)

CdbContainer::SetPermissions, GetPermissions Property

Sets or returns a value that establishes the permissions for the user or group identified by the UserName property of a Container or Document object (Microsoft Jet workspaces only).

Syntax

VOIDSetPermissions(LONG l);

LONGGetPermissions(VOID);

Set Parameters

Type | Example | Description
LONG | l | A Long that contains values as listed in Remarks.

Remarks

The following are valid values:

Constant | Description
dbSecNoAccess | The user doesn't have access to the object.
dbSecFullAccess | The user has full access to the object.
dbSecDelete | The user can delete the object.
dbSecReadSec | The user can read the object's security-related information.
dbSecWriteSec | The user can alter access permissions.
dbSecWriteOwner | The user can change the Owner property setting.


Inherit Property (dbDAO)

CdbContainer::SetInherit, GetInherit Property

Sets or returns a Boolean value that indicates whether new Document objects will inherit a default Permissions property setting (Microsoft Jet workspaces only).

Syntax

VOIDSetInherit(BOOL b);

BOOLGetInherit(VOID);

Set Parameters

Type | Example | Description
BOOL | b | A Boolean. If TRUE, Document objects inherit a default Permissions property setting.


Description Property (dbDAO)

CdbError::GetDescription Property

Returns a descriptive string associated with an error.

Syntax

CStringGetDescription(VOID);


Source Property (dbDAO)

CdbError::GetSource Property

Returns the name of the object or application that originally generated the error.

Syntax

CStringGetSource(VOID);


HelpContext Property (dbDAO)

CdbError::GetHelpContext Property

Returns a context ID for a topic in a Microsoft Windows Help file.

Syntax

LONGGetHelpContext(VOID);


Number Property (dbDAO)

CdbError::GetNumber Property

Returns a numeric value specifying an error.

Syntax

LONGGetNumber(VOID);

Remarks

Use the Number property to determine the error that occurred. The value of the property corresponds to a unique trap number that corresponds to an error condition. For a complete list of all trap numbers and error conditions, see Trappable Microsoft Jet and DAO Errors.


CdbError Constructor (dbDAO)

CdbError Constructor

Syntax Summary

CONSTRUCTORCdbError(VOID);

CONSTRUCTORCdbError(const CdbError &);

CONSTRUCTORCdbError(DAOError *perr,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax / Parameters / Remarks

CONSTRUCTORCdbError(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax / Parameters / Remarks

CONSTRUCTORCdbError(const CdbError &);

Type | Description
const CdbError & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax / Parameters / Remarks

CONSTRUCTORCdbError(DAOError *perr,

BOOL bAddRef=FALSE);

Type | Example | Description
DAOError * | perr | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


HelpFile Property (dbDAO)

CdbError::GetHelpFile Property

Returns a string that is a fully qualified path to the Help file.

Syntax

CStringGetHelpFile(VOID);


Value Property (dbDAO)

CdbProperty::SetValue, GetValue Property

Sets or returns the value of a CdbProperty object.

Syntax

VOIDSetValue(LPVARIANT pv);

COleVariantGetValue(VOID);

Set Parameters

Type | Example | Description
LPVARIANT | pv | A pointer to a COleVariant that contains the value to be inserted into the CdbProperty object.


Name Property (dbDAO)

CdbProperty::SetName, GetName Property

Sets or returns a user-defined name for a CdbProperty object.

Settings and Return Values

The setting or return value is a string that specifies a name. The name must start with a letter. The maximum number of characters is 64. It can include numbers and underscore characters but can't include punctuation or spaces.

Syntax

VOIDSetName(LPCTSTR pstrName);

CStringGetName(VOID);

Set Parameters

Type | Example | Description
LPCTSTR | pstrName | A pointer to a string containing a user-defined name for a CdbProperty object.


Type Property (dbDAO)

CdbProperty::SetType, GetType Property

Sets or returns a value that indicates the data type of an CdbProperty object.

Syntax

VOIDSetType(SHORT sType);

SHORTGetType(VOID);

Set Parameters

Type | Example | Description
SHORT | s | An integer with one of the values shown in Remarks.

Remarks

Constant | Description
dbBigInt | Big Integer
dbBinary | Binary
dbBoolean | Boolean
dbByte | Byte
dbChar | Char
dbCurrency | Currency
dbDate | Date/Time
dbDecimal | Decimal
dbDouble | Double
dbFloat | Float
dbGUID | GUID
dbInteger | Integer
dbLong | Long
dbLongBinary | Long Binary (OLE Object)
dbMemo | Memo
dbNumeric | Numeric
dbSingle | Single
dbText | Text
dbTime | Time
dbTimeStamp | Time Stamp
dbVarBinary | VarBinary


CdbProperty Constructor (dbDAO)

CdbProperty Constructor

Syntax Summary

CONSTRUCTORCdbProperty(VOID);

CONSTRUCTORCdbProperty(const CdbProperty &);

CONSTRUCTORCdbProperty(DAOProperty *pprp,

BOOL bAddRef=FALSE);

(The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.)

Syntax / Parameters / Remarks

CONSTRUCTORCdbProperty(VOID);

This constructor creates an instance of the class. There are no parameters.

Syntax / Parameters / Remarks

CONSTRUCTORCdbProperty(const CdbProperty &);

Type | Description
const CdbProperty & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax / Parameters / Remarks

CONSTRUCTORCdbProperty(DAOProperty *pprp,

BOOL bAddRef=FALSE);

Type | Example | Description
DAOProperty * | pprp | A DAO Automation interface pointer corresponding to this DAO class.
BOOL | bAddRef =FALSE | Optional. A Boolean. If TRUE, the DAO Automation interface AddRef function is called.

DAO functionality is presented through pointers to DAO Automation interfaces. This constructor makes a DAO interface available in the form of a DAO class object that provides additional functionality.

This constructor is not required for typical use. It is provided to allow easy creation of a DAO class object for those with access to the corresponding DAO interface.

When the destructor for the DAO object is invoked, the underlying Automation interface's Release member is called. If Release decrements the interface's reference count to zero, the pointer to the Automation interface can be deleted. If you don't want this to happen (for example, because you want to discard the DAO object but continue using the Automation interface), specify TRUE for the second parameter. The underlying Automation interface's AddRef member is called, which counterbalances the eventual call to Release.


Inherited Property (dbDAO)

CdbProperty::GetInherited Property

Returns a value that indicates whether a CdbProperty object is inherited from an underlying object.

The return value is a Boolean that is TRUE if the Property object is inherited. For built-in Property objects that represent predefined properties, the only possible return value is FALSE. This property is always FALSE in an ODBCDirect workspace.

Syntax

BOOLGetInherited(VOID);


CdbDBEngine Constructor (dbDAO)

CdbDBEngine Constructor

Function

Create an instance of the Jet Database Engine.

Syntax Summary

CONSTRUCTORCdbDBEngine(const CdbDBEngine &);

CONSTRUCTORCdbDBEngine(DAODBEngine *peng,

BOOL bAddRef=FALSE);

CONSTRUCTORCdbDBEngine(BOOL bPrivate=FALSE,

BOOL bStart=TRUE,

LPCTSTR pstrIniPath=NULL,

LPCTSTR pstrDefUser=NULL,

LPCTSTR pstrDefPW=NULL,

LONG lType=dbUseJet);

Note The qualifier 'CONSTRUCTOR' is merely a decoration provided to help readability. It has no syntactic value.

Syntax / Parameters / Remarks

CONSTRUCTORCdbDBEngine(const CdbDBEngine &);

Type | Description
const CdbDBEngine & | Reference to an object.

This constructor creates a copy of the object referenced in the parameter.

Syntax / Parameters / Remarks

CONSTRUCTORCdbDBEngine(DAODBEngine *peng,

BOOL bAddRef=FALSE);

Type | example | Description
DAODBEngine * | peng | A pointer to an OLE interface whose methods correspond to the resulting DAO class object.
BOOL | bAddRef =FALSE | (Optional) A boolean. If TRUE, the AddRef() function of the OLE interface specified in the first parameter is called.

This constructor places an OLE interface into a DAO object.

Syntax / Parameters / Remarks

CONSTRUCTORCdbDBEngine(BOOL bPrivate=FALSE,

BOOL bStart=TRUE,

LPCTSTR pstrIniPath=NULL,

LPCTSTR pstrDefUser=NULL,

LPCTSTR pstrDefPW=NULL,

LONG lType=dbUseJet);

Type | example | Description
BOOL | bPrivate =FALSE | (Optional) Determines whether Jet Engine is Private or Shared. Each private engine is a new instance of DAO. A Private engine is one way to create secure access to data. A shared engine is common across all instances, enabling shared workspaces, databases, etc. If TRUE, then Private.
BOOL | bStart=TRUE | (Optional) If TRUE, Jet Engine is started when this object is created. If FALSE, the Jet Engine must be started explicitly with the Start method.
LPCTSTR | pstrIniPath =NULL | (Optional) A pointer to a string that is a user-supplied portion of the Windows Registry key containing Microsoft Jet database engine settings or parameters needed for installable ISAM databases.
LPCTSTR | pstrDefUser =NULL | (Optional) A pointer to a string that is the user name used to create the default Workspace when it is initialized.
LPCTSTR | pstrDefPW =NULL | (Optional) A pointer to a string that is the password used to create the default Workspace when it is initialized.
LONG | lType=dbUseJet | (Optional) A value that determines whether the Workspace will be Jet or ODBC (i.e., dbUseJet or dbUseODBC).

This constructor builds a CdbDBEngine object.

This constructor is typically specified without parameters (i.e., using all defaults).

One reason to specify parameters is to create the Jet Database Engine, but postpone starting it. This enables acquiring runtime information, or avoiding runtime conflicts when starting DAO from a user DLL. Another common reason to specify parameters is to create an ODBC Direct workspace.

Usage

#include <afxole.h>
#include <dbdao.h>
...                        // Example 1:
CdbDBEngine   dben1a;          // Create an instance using all defaults.
CdbDBEngine   dben1b( dben1a );    // Copy an existing instance.
...
                              // Example 2:
// Create an instance without using all defaults:
   // Create a private engine; don't start it when constructed; no IniPath, yet;       // no DefaultUser; no password, yet; explicitly ask for a Jet Engine workspace.

   CdbDBEngine dben2(TRUE,FALSE,,,,dbUseJet);
   ...
   // Assume that you get the iniPath and DefaultPassword from the user...

   dben2.SetIniPath(lpctstrIniPath);         // Set the iniPath now.
   dben2.SetDefaultPassword(lpctstrPassword);   // Set the DefaultPassword now.
   dben2.Start();                     // Start the engine now.


BY <Microsoft Jet SQL reserved word>

BY

The BY keyword is used in these contexts:

GROUP BY Clause

ORDER BY Clause


INDEX <Microsoft Jet SQL reserved word>

INDEX

The INDEX keyword is used in these contexts:

CREATE INDEX Statement

DROP Statement


TABLE <Microsoft Jet SQL reserved word>

TABLE

The TABLE keyword is used in these contexts:

ALTER TABLE Statement

CREATE INDEX Statement

CREATE TABLE Statement

DROP Statement

UNION Operation


CREATE <Microsoft Jet SQL reserved word>

CREATE

The CREATE keyword is used in these contexts:

CREATE INDEX Statement

CREATE TABLE Statement


SELECT <Microsoft Jet SQL reserved word>

SELECT

The SELECT keyword is used in these contexts:

SELECT Statement

SELECT ... INTO Statement


WITH <Microsoft Jet SQL reserved word>

WITH

The WITH keyword is used in these contexts:

CREATE INDEX Statement

WITH OWNERACCESS OPTION Declaration


INTO <Microsoft Jet SQL reserved word>

INTO

The INTO keyword is used in these contexts:

INSERT INTO Statement

SELECT ... INTO Statement


DROP <Microsoft Jet SQL reserved word>

DROP

The DROP keyword is used in these contexts:

ALTER TABLE Statement

DROP Statement


JOIN <Microsoft Jet SQL reserved word>

JOIN

The JOIN keyword is used in these contexts:

INNER JOIN Operation

LEFT JOIN, RIGHT JOIN Operations


ASC/DESC <Microsoft Jet SQL reserved words>

ASC/DESC

The ASC and DESC keywords are used in these contexts:

CREATE INDEX Statement

ORDER BY Clause


IN <Microsoft Jet SQL reserved word>

IN

The IN keyword is used in these contexts:

In Operator

IN Clause

SQL Subqueries

TRANSFORM Statement


ON <Microsoft Jet SQL reserved word>

ON

The ON keyword is used in these contexts:

INNER JOIN Operation

LEFT JOIN, RIGHT JOIN Operations


ALL <Microsoft Jet SQL reserved word>

ALL

The ALL keyword is used in these contexts:

ALL, DISTINCT, DISTINCTROW, TOP Predicates

SQL Subqueries

UNION Operation