Retrieving data

The following code example demonstrates how to retreive data.

Create a Command object:

ICommandText* pICommandText;
hr = pIDBCreateCommand->CreateCommand(
     NULL, IID_ICommandText,
     (IUnknown**)&pICommandText);

Set the SQL statement:

hr = pICommandText->SetCommandText(
     DBGUID_DBSQL,
     L"SELECT * FROM testReadStringData");

Create and describe the rowset data structure. This structure contains fields for each column you want accessed, as shown:

IAccessor* pIAccessor;
hr = pICommandText->QueryInterface(IID_IAccessor, (void**)&pIAccessor);

static DBBINDING ExactBindings [1] = {
{
     1, // iOrdinal
     offsetof (ExactlyTheSame,s), // obValue
     0, // No length binding
     0, // No Status binding
     NULL, // No TypeInfo
     NULL, // No Object
     NULL, // No Extensions
     DBPART_VALUE,
     DBMEMOWNER_CLIENTOWNED, // Ignored
     DBPARAMIO_NOTPARAM,
     sizeof(mystr), // number of bytes
     0,
     DBTYPE_WSTR | DBTYPE_BYREF,
     0, // No Precision
     0 // No Scale
}
};

DBBINDSTATUS status[1];
HACCESSOR hAccessor;
HRESULT hr = pIAccessor->CreateAccessor(
     DBACCESSOR_ROWDATA, 1, ExactBindings,
     sizeof(ExactlyTheSame), &hAccessor, status);
pIAccessor->Release();

Execute the rowset:

DBROWCOUNT cRowsAffected;
IRowset* pIRowset;
hr = pICommandText->Execute(
NULL, IID_IRowset, params,
&cRowsAffected, (IUnknown**)&pIRowset);

The following code demonstrates getting the rows one at a time:

DBCOUNTITEM cRowsReturned;
HROW hRow[1];
HROW* pRow = hRow;
hr = pIRowset->GetNextRows(NULL, 0, 1, &cRowsReturned, &pRow);

Use IMalloc to free the memory allocated by GetData:

CComPtr<IMalloc> pIMalloc = NULL;
hr = CoGetMalloc( MEMCTX_TASK, &pIMalloc );

while (hr == S_OK)
{

Retrieve the data for the specified row:

     ExactlyTheSame pData[1] = { {NULL} };
     hr = pIRowset->GetData(hRow[0], hAccessor, pData);
     wchar_t* value = pData[0].s;

Free the allocated memory:

     // client owned memory must be freed by the client
     pIMalloc->Free(pData[0].s);
     pData[0].s = NULL;

Release the rows:

     hr = pIRowset->ReleaseRows(1, pRow, NULL, NULL, NULL);

Get the next row:

     hr = pIRowset->GetNextRows(NULL, 0, 1,
          &cRowsReturned, &pRow);
}

pIRowset->Release();
pICommandText->Release();

To retrieve rows from a database, execute a SELECT statement using ICommandText::Execute. This opens a cursor on the statement. You then use IRowset::GetNextRows to fetch rows through the cursor. When an application frees the statement by releasing the rowset, it closes the cursor.