Click here to Skip to main content
13,343,008 members (54,735 online)
Click here to Skip to main content
Add your own
alternative version


31 bookmarked
Posted 8 Aug 2005

How to use DAO in Visual C++ without MFC

, 26 Mar 2006
Rate this:
Please Sign up or sign in to vote.
Use the #import directive and discover the DAO type library.


If you have ever used Data Access Objects (DAO) both in Visual Basic and Visual C++ with MFC, you must have noticed that in Visual Basic, manipulating Microsoft Access MDB files is a more enjoyable way of spending time than doing it in Visual C++ with MFC. And, you must have thought whether a workaround exists to make working with MDB in Visual C++ as flexible as in Visual Basic.

To solve this problem, let's try to use in Visual C++ the same mechanism as is used in Visual Basic. This mechanism assumes that you should work directly with type libraries. Unlike Visual Basic, which is more adapted for rapid application development and has its own methods for accessing type libraries, in Visual C++, working with type libraries is more preferable through converting the content of the type library into C++ classes with the #import directive.

The best way to understand this is by reading a sample source:

// daocpp.cpp
// Describe the full path to dao360.dll file. Interface files dao360.tlh and
// dao360.tli will be generated automatically during compilation.
// The #import directive creates "DAO" namespace to avoid name conflicts with 
// other libraries. So, all DAO members must be referenced with "DAO::" prefix,
// e.g. DAO::DBEngine

#import <C:\Program Files\Common Files\Microsoft Shared\DAO\dao360.dll>
#include <span class="code-keyword"><stdio.h></span>
#include <span class="code-keyword"><tchar.h></span>

// The following procedure dump_com_error and structure StartOle are borrowed from
// MSDN samples.
// Dump all COM errors to console

void dump_com_error(_com_error &e)
    _tprintf(_T("Oops - hit an error!\n"));
    _tprintf(_T("\tCode = %08lx\n"), e.Error());
    _tprintf(_T("\tCode meaning = %s\n"), e.ErrorMessage());
    _bstr_t bstrSource(e.Source());
    _bstr_t bstrDescription(e.Description());
    _tprintf(_T("\tSource = %s\n"), (LPCTSTR) bstrSource);
    _tprintf(_T("\a\tDescription = %s\n"), (LPCTSTR) bstrDescription);

// If this is placed in the scope of the smart pointers, they must be
// explicitly Release(d) before CoUninitialize() is called. If any reference
// count is non-zero, a protection fault will occur.

struct StartOle {
    StartOle() { CoInitialize(NULL); }
    ~StartOle() { CoUninitialize(); }
} _inst_StartOle;

// From this line everything will be commented with its VB analogue

void main()
    // Dim Dbe As DBEngine
    DAO::_DBEnginePtr Dbe(__uuidof(DAO::DBEngine));
    // Dim CurrDB As Database
    DAO::DatabasePtr CurrDB;
    // Dim stmp As String

    char stmp[1024]; // wide chars not used here for simplicity
    // (COM errors must be handled by C++ try/catch block)

    try {
        // Dbe.CreateDatabase("test.mdb", ";LANGID=0x0419;CP=1251;COUNTRY=7;", 
        // dbVersion40). 
        // (";COUNTRY=7" expression allows using "" date format in queries.
        // dbVersion40 constant creates a database with Access 2000 file format.
        // The value for Access 97 format is dbVersion30)

        CurrDB = Dbe->CreateDatabase("test.mdb", 
         ";LANGID=0x0419;CP=1251;COUNTRY=7;", _variant_t((short) DAO::dbVersion40));
        // Set CurrDB = Dbe.OpenDatabase("test.mdb")

        CurrDB = Dbe->OpenDatabase("test.mdb");
        // stmp = "CREATE TABLE ....."

        strcpy(stmp,"CREATE TABLE Test ( \
                        ARTIST Char(40), \
                        TITLE1 Char(60), \
                        FORMAT1 Char(9), \
                        CATNO Numeric, \
                        PRICE Numeric, \
                        DATEIN DateTime, \
                        NOTES Char(10) \
        // CurrDB.Execute(stmp)

        // stmp = "INSERT INTO ....."

        strcpy(stmp,"INSERT INTO Test VALUES( \
                        \"Artist\", \
                        \"Title\", \
                        \"Format1\", \
                        1223, \
                        3231.54, \
                        '21.09.04', \
                        \"Notes\" \
        // CurrDB.Execute(stmp)

        // for i=0 to CurrDB.TableDefs.Count

        // (for all tables in database including system tables)

        for (int i=0; i < CurrDB->TableDefs->Count; i++)
            // Debug.Print CurrDB.TableDefs(i).Name

            _variant_t vI = _variant_t((long) i);
            printf("%s\n", (char *) CurrDB->TableDefs->Item[vI]->Name);
    } catch(_com_error &e) {

Compile this example in the command line as:

cl -GX daocpp.cpp

and run daocpp.exe. The database file test.mdb will be created. This file will contain the table Test with one record of data.

As you can see, the types DBEngine and Database are mapped to the DAO::_DBEnginePtr and DAO::DatabasePtr C++ classes after incorporating information from the type library. The type TableDef will be mapped to _TableDefPtr.

Note: Using DAO requires converting C++ types to the variant type. In this sample, you can see that the C++ type long is converted to the type _variant_t:

_variant_t vI = _variant_t((long) i);

In the same way, for example, the logical values True and False of the bool type will be converted to the type _variant_t as:

_variant_t vTrue = _variant_t((bool) -1);
_variant_t vFalse = _variant_t((bool) 0);

I hope this short article will help you to write more efficient code in your applications.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Yuriy Tkachenko
Software Developer Kiev Computer Laboratory
Ukraine Ukraine
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionUsing querydefs in DAO Pin
VinayChoudhary992-Oct-11 21:57
memberVinayChoudhary992-Oct-11 21:57 
Questioncan someone show how to read MS Access by using DAO Pin
bskorodo15-Dec-08 16:22
memberbskorodo15-Dec-08 16:22 
GeneralThanks for the suggestions on using DAO as a COM object. Pin
CodeWizard195117-Apr-08 10:40
memberCodeWizard195117-Apr-08 10:40 
QuestionCan Somebody show this in standard C rather than C++ Pin
ConceptualCoder14-Aug-06 21:50
memberConceptualCoder14-Aug-06 21:50 
GeneralProblem with OpenRecordset [modified] Pin
nhthiemsvt31-May-06 18:31
membernhthiemsvt31-May-06 18:31 
QuestionErrors at compling Pin
Roey C25-Mar-06 4:08
memberRoey C25-Mar-06 4:08 
AnswerRe: Errors at compling Pin
Yuriy Tkachenko26-Mar-06 2:55
memberYuriy Tkachenko26-Mar-06 2:55 
GeneralUnable to compile it Pin
BilloKhan3-Mar-06 16:50
memberBilloKhan3-Mar-06 16:50 
GeneralRe: Unable to compile it Pin
Yuriy Tkachenko4-Mar-06 8:42
memberYuriy Tkachenko4-Mar-06 8:42 
GeneralRe: Unable to compile it Pin
FCPACHECO13-Aug-10 6:19
memberFCPACHECO13-Aug-10 6:19 
GeneralRe: Unable to compile it Pin
prompete16-Nov-10 4:02
memberprompete16-Nov-10 4:02 
General&quot;no_namespace&quot; issue Pin
mikanu10-Aug-05 15:16
membermikanu10-Aug-05 15:16 
GeneralRe: &quot;no_namespace&quot; issue Pin
yuriytk12-Aug-05 1:23
memberyuriytk12-Aug-05 1:23 
GeneralRe: &amp;quot;no_namespace&amp;quot; issue Pin
Stone Free26-Mar-06 23:24
memberStone Free26-Mar-06 23:24 
QuestionWhere is the &quot;better alternative&quot; in your work? Pin
WREY9-Aug-05 6:43
memberWREY9-Aug-05 6:43 
AnswerRe: Where is the &quot;better alternative&quot; in your work? Pin
mikanu9-Aug-05 12:34
membermikanu9-Aug-05 12:34 
GeneralRe: Where is the &quot;better alternative&quot; in your work? Pin
WREY9-Aug-05 12:53
memberWREY9-Aug-05 12:53 
GeneralRe: Where is the &quot;better alternative&quot; in your work? Pin
mikanu10-Aug-05 9:52
membermikanu10-Aug-05 9:52 
GeneralRe: Where is the &quot;better alternative&quot; in your work? Pin
yuriytk12-Aug-05 0:52
memberyuriytk12-Aug-05 0:52 
GeneralRe: Where is the &quot;better alternative&quot; in your work? Pin
yuriytk12-Aug-05 0:53
memberyuriytk12-Aug-05 0:53 
AnswerRe: Where is the "better alternative" in your work? Pin
yuriytk12-Aug-05 0:45
memberyuriytk12-Aug-05 0:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 26 Mar 2006
Article Copyright 2005 by Yuriy Tkachenko
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid