描述:
刚学习COM,我准备做一个三层数据库程序,中间层用一个
COM,客户通过COM查询后台数据库后,COM怎么把所查询到
的数据集返回给客户层,谢谢!最好给个小例子说明。
解决方案1:
GetAgencyInfo([in] BSTR LogName, [out,retval] IDispatch **info)
STDMETHODIMP CCustomer::GetAgencyInfo(BSTR LogName, IDispatch **info)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState())
char sql[SQL_BUFFER];
sprintf(sql,"SELECT * FROM Agency WHERE ID IN(SELECT PID FROM Customer WHERE Customer.LogName=\'%s\')",B2S(LogName));
_RecordsetPtr pRecordSet=NULL,pRecordSetCl />
try {
pRecordSet.CreateInstance(__uuidof(Recordset));
pRecordSet->CursorLocation = adUseClient;
pRecordSet->Open(sql,szConnectString,adOpenKeyset,adLockOptimistic,adCmdText);
pRecordSet->PutRefActiveConnection(NULL);
pRecordSetClone = pRecordSet->Clone(adLockOptimistic);
pRecordSetClone->QueryInterface(IID_IDispatch, (void**)info);
pRecordSet->Close();
pRecordSet = NULL;
} catch ( _com_error &e ) {
_bstr_t wszSource(e.Source());
_bstr_t wszDescription(e.Description());
_bstr_t wszErrorMessage(e.ErrorMessage());
ATLTRACE(_T("%s\n"), (LPCTSTR)wszSource);
ATLTRACE(_T("%s\n"), (LPCTSTR)wszDescription);
ATLTRACE(_T("%s\n"), (LPCTSTR)wszErrorMessage);
}
return S_OK;
}
返回记录集,使用了COM+事务
STDMETHODIMP CUsers::Login(BSTR loginId, BSTR passWord, VARIANT appTitle, LPDISPATCH *adoRs)
{
// TODO: Add your implementation code here
_ConnectionPtr padoConnection = NULL;
_RecordsetPtr padoRecordset = NULL;
CComPtr<IObjectContext> pObjCtx = NULL;
HRESULT hr = S_OK;
_bstr_t strSQLStmt;
try
{
//创建MTS上下文环境
hr = GetObjectContext(&pObjCtx);
// String I/O stream to write SQL statement
basic_stringstream<wchar_t> strSQLStatement;
//创建SQL语句
strSQLStatement<<L"select a.user_name,a.login_id,a.password,"
<< L"a.user_dept,a.casher_no,b.dept_name,c.capability,c.application "
<< L"from hiscomm.dbo.users a(nolock),hiscomm.dbo.dept_dict b(nolock),"
<< L"hiscomm.dbo.app_grants c(nolock)";
//转换成bstr_t
strSQLStmt = strSQLStatement.str().c_str();
//连接数据库
hr = OpenConnection((LPDISPATCH*)&padoConnection);
//执行SQL语句
padoRecordset=padoConnection->Execute(strSQLStmt,NULL,adCmdText);
//无连接记录
padoRecordset->PutRefActiveConnection(NULL);
if (padoConnection)
{
padoConnection->Close();
}
padoRecordset->QueryInterface(IID_IDispatch,(void **)adoRs);
if (pObjCtx)
pObjCtx->SetComplete();
}
//返回错误信息
catch(_com_error &e)
{
BSTR err=e.Description ();
if (pObjCtx)
pObjCtx->SetAbort();
if (padoConnection)
{
padoConnection->Close();
}
hr=e.Error();
return Error(err,NULL,NULL,IID_IUsers,hr);
}
return S_OK;
}
IDispach * rsreturn;////要传出去的接口
* rsreturn = rs.getinterface();
return S_OK;
如果你是用ADO就简单了,封装一下ADO.就可以提供给客户了.
我也是刚接触这个方面得东西,刚自己做了一个,和你的目的一样,也是给用户层返回一个记录集,我是在客户层申请得Recordset,将Recordset传入到com函数中返回得数据集……方法很笨,呵呵
解决方案6: to bingmatong(*闷声发大财*) ,
GetRecordSet([in] BSTR Query, [out,retval] IDispatch **pRecordSet)
Recordset本来就是一个COM对象,在其它支持COM的语言中可以声明一个指针或对象。可以说是与语言无关的。
... get_Rst([out,retval]IRecordset** pVal)
给用户层返回一个记录集Recordset