C++ ADO Select Sample


ADO is the norm of the day for database programming. It has a set of COM classes with the capability to support all kinds of database operations. This following sample code describes how to retrieve a set of records from a table.
The sample first creates a connection string for the SQL Server database. It then instantiates the Record set interface, with a call to the CoCreateInstance. Any call to the CoCreateInstance should be preceded with a CoInitialize or CoInitializeEx at least once during the life time of the program.
The reason behind this call is to initialize the COM libraries. After this call any COM call can be made. We call our ADO COM interfaces for opening the Record set object first with our select query.

The C++ ADO select query sample below is self explanatory. If you want to execute the code, copy and paste the code in a Win32 or console application and compile the program.


#include <windows.h>
#include <stdio.h>

#import "C:Program FilesCommon FilesSystemADOmsado15.dll"
no_namespace rename("EOF", "EndOfFile")

int main(int argc, char* argv[])
{

HRESULT hr = S_OK;
try
{
CoInitialize(NULL);
        // Define string variables.
_bstr_t strCnn("Provider=SQLOLEDB.1;Persist Security Info=False;User       ID=username;Password=passwd;Initial Catalog=database;Data Source=(local);Integrated Security=SSPI;");

_RecordsetPtr pRstAuthors = NULL;

// Call Create instance to instantiate the Record set
hr = pRstAuthors.CreateInstance(__uuidof(Recordset));

if(FAILED(hr))
{
printf("Failed creating record set instancen");
return 0;
}

//Open the Record set for getting records from Author table
pRstAuthors->Open("SELECT Author_ID,username FROM Author",strCnn, adOpenStatic,     adLockReadOnly,adCmdText);

//Declare a variable of type _bstr_t
_bstr_t valField1;
int valField2;

pRstAuthors->MoveFirst();

//Loop through the Record set
if (!pRstAuthors->EndOfFile)
{
while(!pRstAuthors->EndOfFile)
{
valField1 = pRstAuthors->Fields->GetItem("username")->Value;
valField2 = pRstAuthors->Fields->GetItem("Author_ID")->Value.intVal;
printf("%d - %sn",valField2,(LPCSTR)valField1);
pRstAuthors->MoveNext();
}
}

}
catch(_com_error & ce)
{
printf("Error:%sn",ce.Description);
}

CoUninitialize();
return 0;
}