VC连接SQL2005(例子ADO_2)

 

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

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

01 (2)    void CADO_2Dlg::OnBtnQuery()
02  
03 {
04  
05        CoInitialize(NULL);                                                        // 初始化COM库
06  
07        _ConnectionPtr pConn(__uuidof(Connection));          // 建立Connection
08  
09        _RecordsetPtr pRst(__uuidof(Recordset));          // 建立Recordset
10  
11   
12  
13        _CommandPtr pCmd(__uuidof(Command));                     // 建立Command
14  
15   
16  
17        try
18  
19        {
20  
21               //pConn->ConnectionString = "Provider=SQLOLEDB;Password=XXX;Persist Security Info=True;User ID=sa;Initial Catalog=pubs";       //此句正确
22  
23               pConn->ConnectionString = "driver={SQL Server};Server=(local);DATABASE=pubs;UID=sa;PWD=xxx";
24  
25               pConn->Open("""""", adConnectUnspecified);
26  
27   
28  
29               //pRst = pConn->Execute("select * from authors", NULL, adCmdText);
30  
31               //pRst->Open("select * from authors", _variant_t((IDispatch*) pConn), adOpenDynamic, adLockOptimistic, adCmdText);
32  
33               pCmd->put_ActiveConnection(_variant_t((IDispatch*) pConn));
34  
35               pCmd->CommandText = "select * from authors";
36  
37               pRst = pCmd->Execute(NULL, NULL, adCmdText);
38  
39   
40  
41   
42  
43               while(!pRst->rsEOF)
44  
45               {
46  
47                      ((CListBox*)GetDlgItem(IDC_LIST1))->AddString((_bstr_t)pRst->GetCollect("au_lname")); //查询au_lname字段
48  
49                      pRst->MoveNext();
50  
51               }
52  
53        }
54  
55        catch(_com_error e)
56  
57        {
58  
59               CString errormessage;
60  
61               errormessage.Format("Error: %s", e.ErrorMessage());
62  
63               AfxMessageBox(errormessage);
64  
65        }
66  
67   
68  
69        AfxMessageBox("查询结束!");
70  
71   
72  
73        pRst->Close();
74  
75        pConn->Close();
76  
77        pRst.Release();                                                               // 释放相应COM接口上的引用计数
78  
79        pConn.Release();
80  
81        CoUninitialize();                                                       // 卸载COM库
82  
83 }

 

你可能感兴趣的:(sql2005)