bsp; ,adodb::locktypeenum locktype//=ado20::adlockoptimistic
,long loptions//=adcmdunspecified
)
{
_bstr_t bstrquery;
const tchar _afxparameters2[] = _t("parameters ");
const tchar _afxselect2[] = _t("select ");
const tchar _afxtransform2[] = _t("transform ");
const tchar _afxtable2[] = _t("table ");
// construct the default query string
if ((_tcsnicmp(lpszsql, _afxselect2, _countof(_afxselect2)-1) != 0) &&
(_tcsnicmp(lpszsql, _afxparameters2, _countof(_afxparameters2)-1) != 0) &&
(_tcsnicmp(lpszsql, _afxtransform2, _countof(_afxtransform2)-1) != 0) &&
(_tcsnicmp(lpszsql, _afxtable2, _countof(_afxtable2)-1) != 0)){
cstring strtemp;
strtemp.format("select * from (%s)",lpszsql);
bstrquery=(lpctstr)strtemp;
}
else
bstrquery=lpszsql;
if(rst!=null){
rst->cursorlocation=adodb::aduseclient;
rst->open(bstrquery,_variant_t(pconnection.getinterfaceptr(),true),cursortype,locktype,loptions);
}
trace("open recordset:%s\n",lpszsql);
return esrecordsetisopen(rst);
}
bool esrecordsetisopen(const adodb::_recordsetptr& rst)
{
if(rst!=null){
return rst->state&adodb::adstateopen;
}
return false;
}
void esrecordsetclose(adodb::_recordsetptr& rst)
{
if(rst!=null){
if(rst->state&adodb::adstateopen)
rst->close();
}
}
cstring g_getvaluestring(const _variant_t& val)
{
cstring strval;
_variant_t vardest(val);
if(!g_varisvalid(val)){
return strval;
}
if(val.vt==vt_bool){
if(val.boolval==variant_false){
return _t("否");
}
else
return _t("是");
}
else{
}
if(vardest.vt!=vt_bstr){
hresult hr=::variantchangetype(&vardest,&vardest,variant_nouseroverride|variant_localbool,vt_bstr);
if(failed(hr)){
return strval;
}
}
strval=(lpctstr)_bstr_t(vardest);
return strval;
}
错误处理代码
void eserrprintcomerror(_com_error &e)
{
_bstr_t bstrsource(e.source());
_bstr_t bstrdescription(e.description());
cstring strtemp;
strtemp.format(_t("′错误\n\t错误代码: %08lx\n\t含义: %s\n\t来自 : %s\n\t描述 : %s\n"),
e.error(),e.errormessage(),(lpcstr) bstrsource,(lpcstr) bstrdescription);
// print com errors.
::afxmessagebox(strtemp);
#ifdef _debug
afxdebugbreak();
#endif
}
void eserrprintprovidererror(adodb::_connectionptr pconnection)
{
if(pconnection==null) return;
try{
// print provider errors from connection object.
// perr is a record object in the connection's error collection.
adodb::errorptr perr = null;
adodb::errorsptr perrors=pconnection->errors;
if(perrors){
if( (perrors->count) > 0){
long ncount = perrors->count;
// collection ranges from 0 to ncount -1.
for(long i = 0;i < ncount;i++){
perr = perrors->getitem(i);
cstring strtemp;
strtemp.format(_t("\t 错误代码: %x\t%s"), perr->number, perr->description);
}
}
}
}
catch(_com_error &e){
eserrprintcomerror(e);
}
}
总结
在文档/视图/框架架构中集成数据库访问总体来说还是难度不大的。微软提供了很多示例的代码,大部分工作只是把示例代码从其他语言改写到vc。主要的工作是对mfc的文档/视图/框架架构的理解,在适当的时候调用这些代码。
尽管我在打开数据库的同时也打开了一个记录集,但是我并未给出显示记录集内容的代码,这超出了本文的范围。我可以给出的提示是使用现成的数据列表控件来显示,微软知识库文章q229029 sample: adodatagrid.exe demonstrates how to use ado with datagrid control using visual c++可以作为参考。