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
{
private:
   
    // 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

}

CSampleClass::SomeFunction()
{

    HRESULT hr = m_pConn.CoCreateInstance(CLSID_CADOConnection);
    if (FAILED(hr))
    {
        ::AtlMessageBox(m_hWnd, L"CoCreateInstance failed for CLSID_CADOConnection", L"ADO Failure", MB_ICONERROR);
        ATLENSURE_SUCCEEDED(hr);
    }
    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"));
    ATLENSURE_SUCCEEDED(hr);

    // Create the RecordSet object

    hr = m_pRecordSet.CoCreateInstance(CLSID_CADORecordset);
    ATLENSURE_SUCCEEDED(hr);

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

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

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

    //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: , , ,

Programming

Disclaimer

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