Использование OLE DB для доступа к базе данных MSSQL

OLE DB посредством вызова COM interface

#include <comdef.h>
//в stdafx.h вставить #define DBINITCONSTANTS для CLSID_MSDASQL
HRESULT hr;
CoInitialize(NULL); // инициализация COM
CLSID clsid;
hr = CLSIDFromProgID(L"SQLOLEDB", &clsid) ;
IDBInitialize* pIDBInitialize = NULL;
hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,IID_IDBInitialize, (void **) &pIDBInitialize);
if(FAILED(hr)) AfxMessageBox("CoCreateInstance Error!");
// Группа переменных для свойств
const ULONG nProps = 4;
IDBProperties* pIDBProperties;
DBPROP InitProperties[nProps];
DBPROPSET rgInitPropSet;

for (ULONG i = 0; i < nProps; i++ )
{
VariantInit(&InitProperties[i].vValue);
InitProperties[i].dwOptions = DBPROPOPTIONS_REQUIRED;
InitProperties[i].colid = DB_NULLID;
}
InitProperties[0].dwPropertyID = DBPROP_INIT_PROMPT;
InitProperties[0].vValue.vt = VT_I2;
InitProperties[0].vValue.iVal = DBPROMPT_NOPROMPT;
// Первое
InitProperties[1].dwPropertyID = DBPROP_AUTH_INTEGRATED;
InitProperties[1].vValue.vt = VT_BSTR;
InitProperties[1].vValue.bstrVal = SysAllocString(OLESTR("SSPI"));
// Второе
InitProperties[2].dwPropertyID = DBPROP_INIT_DATASOURCE;
InitProperties[2].vValue.vt = VT_BSTR;
InitProperties[2].vValue.bstrVal = SysAllocString(OLESTR("NONAME-15FCB4E8\\MyServerSQL"));
InitProperties[3].dwPropertyID = DBPROP_INIT_CATALOG;
InitProperties[3].vValue.vt = VT_BSTR;
InitProperties[3].vValue.bstrVal = SysAllocString(OLESTR("D:\\MyBDMSSQL\\MyMSSQL.MDF"));


// Набор свойств
rgInitPropSet.guidPropertySet = DBPROPSET_DBINIT;
rgInitPropSet.cProperties = nProps;
rgInitPropSet.rgProperties = InitProperties;

// Получаем интерфес свойств
pIDBInitialize->QueryInterface(IID_IDBProperties, (void**)&pIDBProperties);
// устанавливаем свойства
hr = pIDBProperties->SetProperties(1, &rgInitPropSet);
if(FAILED(hr)) AfxMessageBox("SetProperties Error!");
// Освобождаем строки
SysFreeString(InitProperties[1].vValue.bstrVal);
SysFreeString(InitProperties[2].vValue.bstrVal);
SysFreeString(InitProperties[3].vValue.bstrVal);
// Освобождаем интерфейс
pIDBProperties->Release();

hr = pIDBInitialize->Initialize();
if(FAILED(hr)) AfxMessageBox("Initialize Failed");
// Группа переменных для сесии
IDBCreateSession* pIDBCreateSession;
IDBCreateCommand* pIDBCreateCommand;
hr=pIDBInitialize->QueryInterface(IID_IDBCreateSession, (void**) &pIDBCreateSession);
if (FAILED(hr)) AfxMessageBox("Create Session Failed");
hr = pIDBCreateSession->CreateSession(NULL, IID_IDBCreateCommand,(IUnknown**) &pIDBCreateCommand);
if (FAILED(hr)) AfxMessageBox("Create Command Failed");

ICommandText* pICommandText;
hr = pIDBCreateCommand->CreateCommand(NULL, IID_ICommandText,(IUnknown**) &pICommandText);
if (FAILED(hr)) AfxMessageBox("Command Create Command Failed");
pIDBCreateCommand->Release();
LPCOLESTR wSQLString = OLESTR("SELECT * FROM Table1");

pICommandText->SetCommandText(DBGUID_DBSQL, wSQLString);
IRowset* pIRowset;
LONG cRowsAffected;
hr = pICommandText->Execute(NULL, IID_IRowset, NULL,&cRowsAffected, (IUnknown**) &pIRowset);
if (FAILED(hr)) AfxMessageBox("Execute Failed");
pICommandText->Release();
//Группа переменных для получения данных о таблицы
IColumnsInfo* pIColumnsInfo;
ULONG nCols;
DBCOLUMNINFO* pColumnsInfo = NULL;
OLECHAR* pColumnStrings = NULL;
// переменные для получения структуры колонок и создания Accessor
DBBINDING* pDBBindings;
ULONG cbRow = 0;
IAccessor* pIAccessor;
HACCESSOR hAccessor;
DBBINDSTATUS* pDBBindStatus = NULL;
// переменные для сток
ULONG cRowsObtained;
HROW rghRows[NUMROWS_CHUNK];
HROW* pRows = &rghRows[0];
char* pRowValues;
hr=pIRowset->QueryInterface(IID_IColumnsInfo, (void**)&pIColumnsInfo);
hr = pIColumnsInfo->GetColumnInfo(&nCols, &pColumnsInfo,&pColumnStrings);
pDBBindings = new DBBINDING[nCols];
for (ULONG nCol = 0; nCol < nCols; nCol++) {
pDBBindings[nCol].iOrdinal = nCol+1;
pDBBindings[nCol].obValue = cbRow;
pDBBindings[nCol].obLength = 0;
pDBBindings[nCol].obStatus = 0;
pDBBindings[nCol].pTypeInfo = NULL;
pDBBindings[nCol].pObject = NULL;
pDBBindings[nCol].pBindExt = NULL;
pDBBindings[nCol].dwPart = DBPART_VALUE;
pDBBindings[nCol].dwMemOwner = DBMEMOWNER_CLIENTOWNED;
pDBBindings[nCol].eParamIO = DBPARAMIO_NOTPARAM;
pDBBindings[nCol].cbMaxLen = pColumnsInfo[nCol].ulColumnSize + 1;
pDBBindings[nCol].dwFlags = 0;
//pDBBindings[nCol].wType = pColumnsInfo[nCol].wType;
pDBBindings[nCol].wType = DBTYPE_WSTR;
pDBBindings[nCol].bPrecision = pColumnsInfo[nCol].bPrecision;
pDBBindings[nCol].bScale = pColumnsInfo[nCol].bScale;
cbRow += pDBBindings[nCol].cbMaxLen;
}
pRowValues = new char[cbRow];
hr=pIRowset->QueryInterface(IID_IAccessor, (void**) &pIAccessor);
pDBBindStatus = new DBBINDSTATUS[nCols];
pIAccessor->CreateAccessor(DBACCESSOR_ROWDATA,nCols,
pDBBindings,0,&hAccessor,pDBBindStatus);
while (TRUE) {
pIRowset->GetNextRows(0,0,NUMROWS_CHUNK,&cRowsObtained,&pRows );
if (cRowsObtained == 0) break;
for (ULONG iRow=0; iRow < cRowsObtained; iRow++)
{
hr = pIRowset->GetData(rghRows[iRow], hAccessor, pRowValues);
if(FAILED(hr)) AfxMessageBox("GetData IRowset Failed!");
//printf("\t%s\n",&pRowValues[pDBBindings[1].obValue]);
CString str;
str.Format("%s - %s - %s",
&pRowValues[pDBBindings[0].obValue],
&pRowValues[pDBBindings[1].obValue],
&pRowValues[pDBBindings[2].obValue]
);
AfxMessageBox(str);
}
}


delete [] pRowValues;
delete [] pDBBindStatus;
delete [] pDBBindings;
pIAccessor->ReleaseAccessor(hAccessor, NULL);
pIAccessor->Release();
pIRowset->Release();
pIColumnsInfo->Release();
pIDBInitialize->Uninitialize();
pIDBInitialize->Release();
// Деинициализация COM
CoUninitialize();

Доступ к базе данных OLE DB использование template

#include <atldbcli.h>

class myNwCust
{
public:
// data elements
TCHAR m_kod[4];
TCHAR m_pname[25];
TCHAR m_psoname[25];

// column binding -- I only want these 4 fields
BEGIN_COLUMN_MAP(myNwCust)
COLUMN_ENTRY(1, m_kod)
COLUMN_ENTRY(2, m_pname)
COLUMN_ENTRY(3, m_psoname)
END_COLUMN_MAP()
};

#include <afxdb.h>
#include <atlbase.h>
#include <comdef.h>

//------------------------------
//ВАРИАНТ #1

CDataSource ds;
CSession session;
CCommand <CAccessor<myNwCust>> cust;

HRESULT hr;

CoInitialize(0);

CDBPropSet dbinit(DBPROPSET_DBINIT);
//dbinit.AddProperty( DBPROP_AUTH_PASSWORD, "");
//dbinit.AddProperty(DBPROP_AUTH_USERID, "" );
dbinit.AddProperty(DBPROP_AUTH_INTEGRATED, OLESTR("SSPI"));
dbinit.AddProperty(DBPROP_INIT_CATALOG, OLESTR("D:\\MyBDMSSQL\\MyMSSQL.MDF"));
dbinit.AddProperty(DBPROP_INIT_DATASOURCE, OLESTR("NONAME-15FCB4E8\\MyServerSQL"));
//dbinit.AddProperty(DBPROP_INIT_PROMPT, (short)4);
//dbinit.AddProperty(DBPROP_INIT_TIMEOUT, (short) 20 );
//dbinit.AddProperty(DBPROP_INIT_GENERALTIMEOUT,(short) 20 );


hr = ds.Open( "SQLOLEDB.1", &dbinit);
if(FAILED(hr))
{
AfxMessageBox("Error ds.Open()");
}

//ds.OpenFromInitializationString(L"Provider=SQLOLEDB.1; Data Source=NONAME-15FCB4E8\\MyServerSQL; Initial File Name=D:\\MyBDMSSQL\\MyMSSQL.mdf;; Integrated Security=SSPI;");

session.Open(ds);

TCHAR mySQL[] = "SELECT * FROM Table1;";

CDBPropSet propset(DBPROPSET_ROWSET);
propset.AddProperty(DBPROP_CANFETCHBACKWARDS, true);
propset.AddProperty(DBPROP_IRowsetChange, true);
propset.AddProperty(DBPROP_UPDATABILITY, DBPROPVAL_UP_CHANGE);

cust.Open(session, "SELECT * FROM Table1;", &propset);

while(cust.MoveNext() == S_OK)
{
CString str;
str = cust.m_pname;
str+= " - ";
str+= cust.m_psoname;

AfxMessageBox(str);
}

cust.Close();
session.Close();
ds.Close();

//--------------------------------------
//ВАРИАНТ #2


CoInitialize(NULL); // инициализация COM

CDataSource ds;
CSession session;
// связь
CCommand<CDynamicAccessor,CRowset> cust;

CDBPropSet dbinit(DBPROPSET_DBINIT);
//dbinit.AddProperty( DBPROP_AUTH_PASSWORD, "");
//dbinit.AddProperty(DBPROP_AUTH_USERID, "" );
dbinit.AddProperty(DBPROP_AUTH_INTEGRATED, OLESTR("SSPI"));
dbinit.AddProperty(DBPROP_INIT_CATALOG, OLESTR("D:\\MyBDMSSQL\\MyMSSQL.MDF"));
dbinit.AddProperty(DBPROP_INIT_DATASOURCE, OLESTR("NONAME-15FCB4E8\\MyServerSQL"));
//dbinit.AddProperty(DBPROP_INIT_PROMPT, (short)4);
//dbinit.AddProperty(DBPROP_INIT_TIMEOUT, (short) 20 );
//dbinit.AddProperty(DBPROP_INIT_GENERALTIMEOUT,(short) 20 );


HRESULT hr = ds.Open( "SQLOLEDB.1", &dbinit);
if(FAILED(hr))
{
AfxMessageBox("Error ds.Open()");
}


//ds.OpenFromInitializationString(L"Provider=SQLOLEDB.1; Data Source=NONAME-15FCB4E8\\MyServerSQL; Initial File Name=D:\\MyBDMSSQL\\MyMSSQL.mdf;; Integrated Security=SSPI;");

hr = session.Open(ds);
if(FAILED(hr))
{
AfxMessageBox("Error session.Open()");
}


TCHAR mySQL[] = "SELECT * FROM Table1;";

CDBPropSet propset(DBPROPSET_ROWSET);
propset.AddProperty(DBPROP_CANFETCHBACKWARDS, true);
propset.AddProperty(DBPROP_IRowsetChange, true);
propset.AddProperty(DBPROP_UPDATABILITY, DBPROPVAL_UP_CHANGE);

hr = cust.Open(session, "SELECT * FROM Table1;", &propset);
if(FAILED(hr))
{
AfxMessageBox("Error cust.Open()");
}


hr = cust.MoveFirst();
while(S_OK == hr) {

int * num =(int*)cust.GetValue(_T("kod"));
char * name =(char*) cust.GetValue(_T("pname"));
char * soname =(char*) cust.GetValue(_T("psoname"));

CString str;

str.Format("%d - %s - %s", *num, name, soname);

AfxMessageBox(str);


hr = cust.MoveNext();
}
cust.Close();
session.Close();
ds.Close();




Доступ к базе данных OLE DB использование stored procedure посредством COM interafce

#include <atldbcli.h>

class myNwCust
{
public:
// data elements
TCHAR m_kod[4];
TCHAR m_pname[25];
TCHAR m_psoname[25];

// column binding -- I only want these 4 fields
BEGIN_COLUMN_MAP(myNwCust)
COLUMN_ENTRY(1, m_kod)
COLUMN_ENTRY(2, m_pname)
COLUMN_ENTRY(3, m_psoname)
END_COLUMN_MAP()
};

typedef struct tagSPROCPARAMS
{
long lReturnValue;
long lkodValue;
} SPROCPARAMS;


#include <oledb.h>
#include <oledberr.h>
#include <SQLOLEDB.h>

//в stdafx.h вставить #define DBINITCONSTANTS для CLSID_MSDASQL
HRESULT hr;
CoInitialize(NULL); // инициализация COM

IDBInitialize* pIDBInitialize = NULL;
hr = CoCreateInstance(CLSID_SQLOLEDB, NULL, CLSCTX_INPROC_SERVER,IID_IDBInitialize, (void **) &pIDBInitialize);
if(FAILED(hr)) AfxMessageBox("CoCreateInstance Error!");
// Группа переменных для свойств
const ULONG nProps = 6;
IDBProperties* pIDBProperties;
DBPROP InitProperties[nProps];
DBPROPSET rgInitPropSet;

for (ULONG i = 0; i < nProps; i++ )
{
VariantInit(&InitProperties[i].vValue);
InitProperties[i].dwOptions = DBPROPOPTIONS_REQUIRED;
InitProperties[i].colid = DB_NULLID;
}
InitProperties[0].dwPropertyID = DBPROP_INIT_PROMPT;
InitProperties[0].vValue.vt = VT_I2;
InitProperties[0].vValue.iVal = DBPROMPT_NOPROMPT;


// Первое
InitProperties[1].dwPropertyID = DBPROP_AUTH_INTEGRATED;
InitProperties[1].vValue.vt = VT_BSTR;
InitProperties[1].vValue.bstrVal = SysAllocString(OLESTR("SSPI"));

// Второе
InitProperties[2].dwPropertyID = DBPROP_INIT_DATASOURCE;
InitProperties[2].vValue.vt = VT_BSTR;
InitProperties[2].vValue.bstrVal = SysAllocString(OLESTR("NONAME-15FCB4E8\\MyServerSQL"));


InitProperties[3].dwPropertyID = DBPROP_INIT_CATALOG;
InitProperties[3].vValue.vt = VT_BSTR;
InitProperties[3].vValue.bstrVal = SysAllocString(OLESTR("D:\\MyBDMSSQL\\MyMSSQL.MDF"));



InitProperties[4].dwPropertyID = DBPROP_OUTPUTPARAMETERAVAILABILITY;
InitProperties[4].vValue.vt = VT_I4;
InitProperties[4].vValue.lVal = DBPROPVAL_OA_ATROWRELEASE;
//InitProperties[4].vValue.lVal = DBPROPVAL_OA_ATEXECUTE;

InitProperties[5].dwPropertyID = DBPROP_MULTIPLEPARAMSETS;
InitProperties[5].vValue.vt = VT_BOOL;
InitProperties[5].vValue.boolVal = VARIANT_TRUE;


// Набор свойств
rgInitPropSet.guidPropertySet = DBPROPSET_DBINIT;
//rgInitPropSet.guidPropertySet = DBPROPSET_DATASOURCEINFO;
rgInitPropSet.cProperties = nProps;
rgInitPropSet.rgProperties = InitProperties;

// Получаем интерфес свойств
pIDBInitialize->QueryInterface(IID_IDBProperties, (void**)&pIDBProperties);
// устанавливаем свойства
hr = pIDBProperties->SetProperties(1, &rgInitPropSet);
if(FAILED(hr)) AfxMessageBox("SetProperties Error!");
// Освобождаем строки
//SysFreeString(InitProperties[1].vValue.bstrVal);
//SysFreeString(InitProperties[2].vValue.bstrVal);
//SysFreeString(InitProperties[3].vValue.bstrVal);
// Освобождаем интерфейс
pIDBProperties->Release();


hr = pIDBInitialize->Initialize();
if(FAILED(hr)) AfxMessageBox("Initialize Failed");

// Группа переменных для сесии
IDBCreateSession* pIDBCreateSession;
IDBCreateCommand* pIDBCreateCommand;


hr=pIDBInitialize->QueryInterface(IID_IDBCreateSession, (void**) &pIDBCreateSession);
if (FAILED(hr)) AfxMessageBox("Create Session Failed");

hr = pIDBCreateSession->CreateSession(NULL, IID_IDBCreateCommand,(IUnknown**) &pIDBCreateCommand);
if (FAILED(hr)) AfxMessageBox("Create Command Failed");


ICommandText* pICommandText;
hr = pIDBCreateCommand->CreateCommand(NULL, IID_ICommandText,(IUnknown**) &pICommandText);
if (FAILED(hr)) AfxMessageBox("Command Create Command Failed");


WCHAR* wSQLString = L"{?=CALL myproc(?)}";

pICommandText->SetCommandText(DBGUID_DBSQL, wSQLString);

SPROCPARAMS sprocparams = {0, 2};

ICommandWithParameters* pICommandWithParameters = NULL;

IMultipleResults* pIMultipleResults = NULL;

DBPARAMS Params;
const ULONG nParams = 2;

hr = pICommandText->QueryInterface(
IID_ICommandWithParameters,
(void**) &pICommandWithParameters);


DBBINDING acDBBinding[nParams];
DBBINDSTATUS acDBBindStatus[nParams];


for (ULONG i = 0; i < nParams; i++)
{
acDBBinding[i].obLength = 0;
acDBBinding[i].obStatus = 0;
acDBBinding[i].pTypeInfo = NULL;
acDBBinding[i].pObject = NULL;
acDBBinding[i].pBindExt = NULL;
acDBBinding[i].dwPart = DBPART_VALUE;
acDBBinding[i].dwMemOwner = DBMEMOWNER_CLIENTOWNED;
acDBBinding[i].dwFlags = 0;
acDBBinding[i].bScale = 0;
}

acDBBinding[0].iOrdinal = 1;
acDBBinding[0].obValue = offsetof(SPROCPARAMS, lReturnValue);
acDBBinding[0].eParamIO = DBPARAMIO_OUTPUT;
//acDBBinding[0].dwMemOwner = DBMEMOWNER_CLIENTOWNED;
acDBBinding[0].cbMaxLen = sizeof(long);
acDBBinding[0].wType = DBTYPE_I4;
acDBBinding[0].bPrecision = 11;


acDBBinding[1].iOrdinal = 2;
acDBBinding[1].obValue = offsetof(SPROCPARAMS, lkodValue);
acDBBinding[1].eParamIO = DBPARAMIO_INPUT;
acDBBinding[1].cbMaxLen = sizeof(long);
acDBBinding[1].wType = DBTYPE_I4;
acDBBinding[1].bPrecision = 11;



IAccessor* pIPAccessor;
HACCESSOR hPAccessor;


pICommandWithParameters->QueryInterface(IID_IAccessor,
(void**) &pIPAccessor);
if(FAILED(hr)) AfxMessageBox("Failed Query Interface IId_IAccessor");


hr = pIPAccessor->CreateAccessor(DBACCESSOR_PARAMETERDATA,
nParams, acDBBinding, sizeof(SPROCPARAMS), &hPAccessor,
acDBBindStatus);
if(FAILED(hr)) AfxMessageBox("Failed Create Accessor");

// Fill the DBPARAMS structure for the command execution.
Params.pData = (void*)&sprocparams;
Params.cParamSets = 1;
Params.hAccessor = hPAccessor;

LONG cRowsAffected;

IRowset* pIRowset;


//Группа переменных для получения данных о таблицы
IColumnsInfo* pIColumnsInfo;
ULONG nCols;
DBCOLUMNINFO* pColumnsInfo = NULL;
OLECHAR* pColumnStrings = NULL;

// переменные для получения структуры колонок и создания Accessor
DBBINDING* pDBBindings;
ULONG cbRow = 0;
DBBINDSTATUS* pDBBindStatus = NULL;

// переменные для сток
ULONG cRowsObtained;
HROW rghRows[NUMROWS_CHUNK];
HROW* pRows = &rghRows[0];
char* pRowValues;

hr = pICommandText->Execute(NULL, IID_IRowset, &Params,&cRowsAffected, (IUnknown**) &pIRowset);
if (FAILED(hr)) AfxMessageBox("Execute Failed");


CString str;

str.Format("%d",sprocparams.lReturnValue);
AfxMessageBox(str);

pIRowset->Release();

str.Format("%d",sprocparams.lReturnValue);
AfxMessageBox(str);

hr = pICommandText->Execute(NULL, IID_IRowset, &Params,&cRowsAffected, (IUnknown**) &pIRowset);
if (FAILED(hr)) AfxMessageBox("Execute Failed");


//-------------------------------


hr=pIRowset->QueryInterface(IID_IColumnsInfo, (void**)&pIColumnsInfo);
hr = pIColumnsInfo->GetColumnInfo(&nCols, &pColumnsInfo,&pColumnStrings);

pDBBindings = new DBBINDING[nCols];

for (ULONG nCol = 0; nCol < nCols; nCol++)
{
pDBBindings[nCol].iOrdinal = nCol+1;
pDBBindings[nCol].obValue = cbRow;
pDBBindings[nCol].obLength = 0;
pDBBindings[nCol].obStatus = 0;
pDBBindings[nCol].pTypeInfo = NULL;
pDBBindings[nCol].pObject = NULL;
pDBBindings[nCol].pBindExt = NULL;
pDBBindings[nCol].dwPart = DBPART_VALUE;
pDBBindings[nCol].dwMemOwner = DBMEMOWNER_CLIENTOWNED;
pDBBindings[nCol].eParamIO = DBPARAMIO_NOTPARAM;
pDBBindings[nCol].cbMaxLen = pColumnsInfo[nCol].ulColumnSize + 1;
pDBBindings[nCol].dwFlags = 0;
//pDBBindings[nCol].wType = pColumnsInfo[nCol].wType;
pDBBindings[nCol].wType = DBTYPE_WSTR;
pDBBindings[nCol].bPrecision = pColumnsInfo[nCol].bPrecision;
pDBBindings[nCol].bScale = pColumnsInfo[nCol].bScale;
cbRow += pDBBindings[nCol].cbMaxLen;
}

pRowValues = new char[cbRow];

IAccessor* pIAccessor;
HACCESSOR hAccessor;


hr=pIRowset->QueryInterface(IID_IAccessor, (void**) &pIAccessor);
pDBBindStatus = new DBBINDSTATUS[nCols];




pIAccessor->CreateAccessor(DBACCESSOR_ROWDATA,nCols,
pDBBindings,0,&hAccessor,pDBBindStatus);


while (TRUE)
{
hr = pIRowset->GetNextRows(0,0,NUMROWS_CHUNK,&cRowsObtained,&pRows );
if (cRowsObtained == 0) break;
for (ULONG iRow=0; iRow < cRowsObtained; iRow++)
{

hr = pIRowset->GetData(rghRows[iRow], hAccessor, pRowValues);
if(FAILED(hr)) AfxMessageBox("GetData IRowset Failed!");
//printf("\t%s\n",&pRowValues[pDBBindings[1].obValue]);
CString str;
str.Format("%s - %s - %s",
&pRowValues[pDBBindings[0].obValue],
&pRowValues[pDBBindings[1].obValue],
&pRowValues[pDBBindings[2].obValue]
);
AfxMessageBox(str);
}

}


//-------------------------------

pIRowset->Release();

str.Format("%d",sprocparams.lReturnValue);
AfxMessageBox(str);




Доступ к базе данных OLE DB использование stored procedure и template

#include <atldbcli.h>

class myNwCust
{
public:
// data elements
TCHAR m_kod[4];
TCHAR m_pname[25];
TCHAR m_psoname[25];

// column binding -- I only want these 4 fields
BEGIN_COLUMN_MAP(myNwCust)
COLUMN_ENTRY(1, m_kod)
COLUMN_ENTRY(2, m_pname)
COLUMN_ENTRY(3, m_psoname)
END_COLUMN_MAP()
};


#include <afxdb.h>
#include <atlbase.h>

#include <comdef.h>


CoInitialize(NULL); // инициализация COM

CDataSource ds;
CSession session;
// связь
CCommand<CDynamicParameterAccessor,CRowset,CMultipleResults> cust;

CDBPropSet dbinit(DBPROPSET_DBINIT);
//dbinit.AddProperty( DBPROP_AUTH_PASSWORD, "");
//dbinit.AddProperty(DBPROP_AUTH_USERID, "" );
dbinit.AddProperty(DBPROP_AUTH_INTEGRATED, OLESTR("SSPI"));
dbinit.AddProperty(DBPROP_INIT_CATALOG, OLESTR("D:\\MyBDMSSQL\\MyMSSQL.MDF"));
dbinit.AddProperty(DBPROP_INIT_DATASOURCE, OLESTR("NONAME-15FCB4E8\\MyServerSQL"));
//dbinit.AddProperty(DBPROP_INIT_PROMPT, (short)4);
//dbinit.AddProperty(DBPROP_INIT_TIMEOUT, (short) 20 );
//dbinit.AddProperty(DBPROP_INIT_GENERALTIMEOUT,(short) 20 );

HRESULT hr = ds.Open( "SQLOLEDB.1", &dbinit);
if(FAILED(hr))
{
AfxMessageBox("Error ds.Open()");
}

hr = session.Open(ds);
if(FAILED(hr))
{
AfxMessageBox("Error session.Open()");
}


hr = cust.Create(session,"{? = CALL myproc(?)}");
hr = cust.Prepare();
void* pDummy;
// Bind the parameters.
hr = cust.BindParameters(&cust.m_hParameterAccessor,
cust.m_spCommand,&pDummy);


int nParamValue = 2;
char *pData=NULL;
// Set the parameter values.
cust.SetParam((ULONG)2,&nParamValue);
// Open the command.
hr=cust.Open(NULL,NULL,0);
cust.Bind();

hr = cust.MoveFirst();
while(S_OK == hr) {

int * num =(int*)cust.GetValue(_T("kod"));
char * name =(char*) cust.GetValue(_T("pname"));
char * soname =(char*) cust.GetValue(_T("psoname"));

CString str;
str.Format("%d - %s - %s", *num, name, soname);
AfxMessageBox(str);


hr = cust.MoveNext();
}

// Now we get the output parameter.

long lOutVal;
hr=cust.GetNextResult(&lOutVal);
// Get the output parameter value.
cust.GetParam((ULONG)1, &lOutVal);

CString str;
str.Format("%d", lOutVal);
AfxMessageBox(str);


session.Close();
ds.Close();