Acquiring the ActiveX Data Objects Automation Interfaces in VC++

ADO exposes its functionality through ADO Automation interfaces. The interfaces can be acquired by calling CoCreateInstance with class and interface IDs named in adoid.h.

The following is an excerpt from the ADO Getrows sample. That sample presents a dialog containing a list, and a button labeled "Execute." When the "Execute" button is pressed the list is populated with records from the Employee table of the OLE_DB_NWind_Jet data source.

First, we ensure that OLE is initialized. Then the Connection and Recordset interfaces are acquired. (Most of the processing and error handling is omitted for readability.)

HRESULT    hr;
        ...
        hr = CoInitialize(NULL);
        if (FAILED(hr)) goto ErrorExit;
 

Next, the Connection interface is instantiated using the Connection class and interface IDs.

        hr = CoCreateInstance(CLSID_CADOConnection,                                 NULL, CLSCTX_INPROC_SERVER,                                     IID_IADOConnection, 
                        (LPVOID *)&m_piConnection);
 

Opening the connection will require BSTR strings specifying the data source, user ID and SQL statement. Those strings are initialized, then the Connection interface is used to open the connection.

        hr = m_piConnection->Open(     bstrSource, bstrUser,                                             NULL ); 
 

The Recordset interface is instantiated using the Recordset class and interface IDs.

        hr = CoCreateInstance(CLSID_CADORecordset, 
                            NULL, CLSCTX_INPROC_SERVER, 
                            IID_IADORecordset, 
                            (LPVOID *)&m_piEmpRecordSet);
 

The Recordset interface can now be used to manipulate recordset properties and methods.

        hr = m_piEmpRecordSet->put_Source(bstrSQL);    
        hr = m_piEmpRecordSet->
            putref_Active­Connection(m_piConnection);        ...
        hr = m_piEmpRecordSet->Open(vNull, vNull, 
                adOpenKeyset, adLockOptimistic);        
        ...
 

The Automation interfaces must be released before the program ends. A convenient place to do this is in the destructor for the dialog object.

CGetRowsDlg::~CGetRowsDlg()
{
    if ( m_piConnection != NULL )
                m_piConnection->Release();             
    if ( m_piEmpRecordSet != NULL )
                m_piEmpRecordSet->Release();            
    m_piConnection = NULL;
    m_piEmpRecordSet = NULL;
}