Using ADO without #import

by Codewiz51 18. April 2011 20:54

Most articles you find on the internet regarding ADO illustrate using #import to do the hardwork of importing the COM object's interface.  However, #import drags in a lot of heavy weight classes that aren't really necessary.

This article illustrates using the header files initguid.h, adoid.h and adoint.h which are included in the Windows SDK (don't worry about the version, the files have been in the SDK for as long as I can remember.) You'll need to download the SDK to use with your development environment.

#include <initguid.h>
#include <adoid.h>
#include <adoint.h>

// Sample class interface

class CSample
    // ADO Interface pointers
    // (We connect to an Access 2000 MDB file)

    CComPtr<_ADOConnection> m_pConn;
    CComPtr<_ADORecordset> m_pRecordSet;

    //More code here
    //Yada yada yada



    HRESULT hr = m_pConn.CoCreateInstance(CLSID_CADOConnection);
    if (FAILED(hr))
        ::AtlMessageBox(m_hWnd, L"CoCreateInstance failed for CLSID_CADOConnection", L"ADO Failure", MB_ICONERROR);
    else if (S_FALSE == hr)
        DWORD dwError = ::GetLastError();
        CString msgErr;
        msgErr.Format(L"CoCreateInstance(CLSID_CADOConnection)\nexperienced a non-failing error\nGetLastError returned %u", dwError);
        ::AtlMessageBox(m_hWnd, (LPCTSTR) msgErr, L"ADO Non Failing Return");

    // Create the connection object

    hr = m_pConn->Open(CComBSTR("Provider=Microsoft.Jet.OLEDB.4.0;Password=\"\";Data Source=.\\DBSAMPLE.mdb;Persist Security Info=True"));

    // Create the RecordSet object

    hr = m_pRecordSet.CoCreateInstance(CLSID_CADORecordset);

    CComVariant RSSource(L"SELECT * FROM [Network - Computers]");
    CComVariant vConn(m_pConn.p);
    hr = m_pRecordSet->put_CursorLocation(adUseClient);

    hr = m_pRecordSet->Open(RSSource, vConn, adOpenKeyset, adLockOptimistic, adCmdText);

    ADO_LONGPTR pl = 0;
    hr = m_pRecordSet->get_RecordCount(&pl);

    //More useful code here
    //Yada yada yada

And that is all there is to using the SDK header files to interface with ADO using ATL or WTL templates.

Tags: , , ,



This blog represents my personal hobby, observations and views. It does not represent the views of my employer, clients, especially my wife, children, in-laws, clergy, the dog, the cat or my daughter's horse. In fact, I am not even sure it represents my views when I take the time to reread postings.  So, take most of what I say with a grain of salt.

© Copyright 2008-2014