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库

}


转载于:https://www.cnblogs.com/joeblackzqq/archive/2010/09/01/1815287.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值