我写了一个从数据库中获得信息并返回的函数
char *GetNotice()
{
_RecordsetPtr pSet;
try
{
HRESULT hr;
hr=pSet.CreateInstance(__uuidof(Recordset));
if(FAILED(hr))
{
//AfxMessageBox("can't create an instance of recordset");
return NOTICE_FAIL;
}
char* strSQL="select info from t_Info";
pSet->Open(_bstr_t(strSQL),_variant_t((IDispatch *)pConn,true),adOpenStatic,adLockOptimistic,adCmdText);
if(pSet->adoEOF)
{
if(pSet!=0 && pSet->State)
{
pSet->Close();
pSet->Release();
}
return NOTICE_FAIL;
}
else
{
char *pInfo=(char *)(_bstr_t)pSet->Fields->GetItem("info")->Value;
if(pSet!=0 && pSet->State)
{
pSet->Close();
//pSet->Release();
}
return pInfo;
}
}
catch(_com_error &e)
{
printf("%s\n",e.ErrorMessage());
if(pSet!=0 && pSet->State)
{
pSet->Close();
//pSet->Release();加上出错?
}
return NOTICE_FAIL;
}
}本意是从数据库中查询信息,然后返回.
1.为什么加上了PSet->Release();后运行异常
2.调用后,并得不到想要的信息,数据库查询成功,可无法获取返回值.
应该如何改?太菜,谢谢啊

解决方案 »

  1.   

    1、pSet是一个智能指针,会自动释放
    2、pInfo是一个局部变量,函数结束后生存期就结束了,可以通过返回CString之类的进行
      

  2.   

    不是MFC
    不能使用CString我已经试过了,定义了全局的char *
    还是一样不知道哪里有问题既然是智能指针,那为什么要设计Release这个方法?
    需要在什么时候调用?愁死人
      

  3.   

    问题已经解决出错是的原因:pSet->Fields->GetItem("info")->Value;
    所得到的是variant_t型的虽然用CString可以用(char *)(_bstr_t)强制转换,但是char *不行
    应该用_com_util::ConvertBSTRToString函数转换成char *
    看来CString 还是挺智能的...