适用ADO与sql2008交互的一个例子

来源:互联网 发布:sql 它代表什么 编辑:程序博客网 时间:2024/05/17 09:07

在控制面板里,先配置数据源

 

这是我从小项目里截取的相关函数,注意部分代码与目的无关,只看相关代码实现即可

//连接指针和数据集指针 

_ConnectionPtr m_pConnection;
 _RecordsetPtr  m_pRecorset;

//实现代码,

void CTableListView::ReadDataSet(){CListCtrl &mList=GetListCtrl();CoInitialize(NULL);    //初始化COM组件m_pConnection=_ConnectionPtr("ADODB.Connection");HRESULT hr;_bstr_t src(L"test");      //此处用之前注册的数据源的名称_bstr_t user(L"(local)");  //此处用local,代表本机用户_bstr_t pwd(L"6869");      //密码可以不用hr=m_pConnection.CreateInstance("ADODB.Connection");if (SUCCEEDED(hr)){//hr=m_pConnection->Open(src,user,pwd,adModeUnknown);hr=m_pConnection->Open(src,user,pwd,adConnectUnspecified);  //打开连接if (SUCCEEDED(hr)){::AfxMessageBox("open source success!");//_bstr_t mSqlStr ="select * from user";HRESULT  hr2=m_pRecorset.CreateInstance(__uuidof( Recordset )); if (SUCCEEDED(hr2)){AfxMessageBox("connect successfully!");try{_bstr_t mSQlstr="select * from \"user\"";m_pRecorset->Open(_variant_t(mSQlstr),m_pConnection.GetInterfacePtr(),adOpenStatic,adLockOptimistic,adCmdText);//CString idStr,nameStr,wStr,hStr;_variant_t vRVariant;int nRow=0;while (!m_pRecorset->EndOfFile){vRVariant=m_pRecorset->Fields->GetItem((long)0)->GetValue();idStr=(char*)(_bstr_t)vRVariant;vRVariant=m_pRecorset->Fields->GetItem((long)1)->GetValue();nameStr=(char*)(_bstr_t)vRVariant;vRVariant=m_pRecorset->Fields->GetItem((long)2)->GetValue();wStr=(char*)(_bstr_t)vRVariant;vRVariant=m_pRecorset->Fields->GetItem((long)3)->GetValue();hStr=(char*)(_bstr_t)vRVariant;m_pRecorset->MoveNext();//将读到数据显示在clistCtrl上
mList.InsertItem(nRow,idStr);mList.SetItemText(nRow, 1, nameStr);//设置数据mList.SetItemText(nRow, 2, wStr);//设置数据mList.SetItemText(nRow, 3, hStr);//设置数据nRow++;}}catch (  _com_error   &e){_bstr_t   bstrSource   (e.Source()); _bstr_t   bstrDescription   (e.Description()); CString   strError; strError.Format( "无法执行数据连接。\r\n错误代码是:%08lx\r\n错误的原因是:%s\r\n错误源是:%s\r\n错误的描述是:%s\r\n ",   e.Error   (),   e.ErrorMessage   (),   (LPCTSTR)   bstrSource,   (LPCTSTR)   bstrDescription); MessageBox   (strError,   bstrDescription,MB_OK); return  ; }catch (CFileException* e){e->ReportError(); e->Delete(); return ; }catch (CException* e){TRACE   (   "***   无法解决的错误   *** "   ); return  ; }}}}}