STDMETHODIMP CMyRsArray::GetRsArray(VARIANT * pvar)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState())
HRESULT hr;
_variant_t var1, var2; // Variants to wrap the recordsets.
// Clear return value.
VariantClear(pvar);
SAFEARRAY * pSA;
// Create the safearray.
SAFEARRAYBOUND sabRSarray[1]; // A one-dimensional array.
sabRSarray[0].cElements=2; // Two elements.
sabRSarray[0].lLbound=0; //Lower bound of array.
pSA=SafeArrayCreate(VT_VARIANT,1, sabRSarray);
try
{
// Create the recordsets.
_RecordsetPtr RS1(__uuidof(Recordset));
_RecordsetPtr RS2(__uuidof(Recordset));
_ConnectionPtr spConn1(__uuidof(Connection));
_ConnectionPtr spConn2(__uuidof(Connection));
// Make sure you pass valid connection properties to connect and get recordsets.
hr=spConn1->Open(OLESTR("dsn=MyDSN"),OLESTR("user_id"),
OLESTR("password"), -1);
hr=spConn2->Open(OLESTR("dsn=MyDSN"),OLESTR("user_id"),
OLESTR("password"), -1);
// Disconnected recordsets must use adUseClient.
RS1->CursorLocation = adUseClient;
RS2->CursorLocation = adUseClient;
hr=RS1->Open(OLESTR("select * from authors"), spConn1.GetInterfacePtr(), adOpenKeyset, adLockBatchOptimistic, adCmdText);
hr=RS2->Open(OLESTR("select * from authors"), spConn2.GetInterfacePtr(), adOpenStatic, adLockBatchOptimistic, -1);
// Disassociate the connection from the recordset.
RS1->PutRefActiveConnection(NULL);
RS2->PutRefActiveConnection(NULL);
// Copy IDispatch pointer of recordset into our _variant_t array.
// This will AddRef the recordset one time (refcount now is 2).
var1 = _variant_t( (IDispatch*) RS1 );
var2 = _variant_t( (IDispatch*) RS2 );
RS1 = NULL;
RS2 = NULL; // refcount now is 1, variants contain last reference to recordsets.
// Fill the safearray.
long ndex;
ndex = 0;
hr=SafeArrayPutElement(pSA, &ndex, &var1);
ndex = 1;
hr=SafeArrayPutElement(pSA, &ndex, &var2);
// Load the safearray into an output variable.
pvar->vt = VT_ARRAY|VT_VARIANT;
pvar->parray = pSA;
}
catch( _com_error e)
{
hr = e.Error();
}
return S_OK;
}