VC连接SQL2005(例子ADO_2)

(1)    在StdAfx.h中添加下面一句话:

#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "rsEOF")

(2)    void CADO_2Dlg::OnBtnQuery() 



{



       CoInitialize(NULL);                                                        // 初始化COM库



       _ConnectionPtr pConn(__uuidof(Connection));          // 建立Connection



       _RecordsetPtr pRst(__uuidof(Recordset));          // 建立Recordset



 



       _CommandPtr pCmd(__uuidof(Command));                     // 建立Command



 



       try



       {



              //pConn->ConnectionString = "Provider=SQLOLEDB;Password=XXX;Persist Security Info=True;User ID=sa;Initial Catalog=pubs";       //此句正确



              pConn->ConnectionString = "driver={SQL Server};Server=(local);DATABASE=pubs;UID=sa;PWD=xxx";



              pConn->Open("", "", "", adConnectUnspecified);



 



              //pRst = pConn->Execute("select * from authors", NULL, adCmdText);



              //pRst->Open("select * from authors", _variant_t((IDispatch*) pConn), adOpenDynamic, adLockOptimistic, adCmdText);



              pCmd->put_ActiveConnection(_variant_t((IDispatch*) pConn));



              pCmd->CommandText = "select * from authors";



              pRst = pCmd->Execute(NULL, NULL, adCmdText);



 



 



              while(!pRst->rsEOF)



              {



                     ((CListBox*)GetDlgItem(IDC_LIST1))->AddString((_bstr_t)pRst->GetCollect("au_lname")); //查询au_lname字段



                     pRst->MoveNext();



              }



       }



       catch(_com_error e)



       {



              CString errormessage;



              errormessage.Format("Error: %s", e.ErrorMessage());



              AfxMessageBox(errormessage);



       }



 



       AfxMessageBox("查询结束!");



 



       pRst->Close();



       pConn->Close();



       pRst.Release();                                                               // 释放相应COM接口上的引用计数 



       pConn.Release();



       CoUninitialize();                                                       // 卸载COM库



}





你可能感兴趣的:(sql2005)