您的位置:首页 > 数据库

VC连接SQL2005(例子ADO_2)

2011-03-30 11:58 274 查看
(1)在StdAfx.h中添加下面一句话:
#import"C:/ProgramFiles/CommonFiles/System/ado/msado15.dll"no_namespacerename("EOF","rsEOF")

viewsourceprint?

01
(2)
void
CADO_2Dlg::OnBtnQuery()
02
03
{
04
05
CoInitialize(NULL);
//初始化COM库
06
07
_ConnectionPtrpConn(__uuidof(Connection));
//建立Connection
08
09
_RecordsetPtrpRst(__uuidof(Recordset));
//建立Recordset
10
11
12
13
_CommandPtrpCmd(__uuidof(Command));
//建立Command
14
15
16
17
try
18
19
{
20
21
//pConn->ConnectionString="Provider=SQLOLEDB;Password=XXX;PersistSecurityInfo=True;UserID=sa;InitialCatalog=pubs";//此句正确
22
23
pConn->ConnectionString=
"driver={SQLServer};Server=(local);DATABASE=pubs;UID=sa;PWD=xxx"
;
24
25
pConn->Open(
""
,
""
,
""
,adConnectUnspecified);
26
27
28
29
//pRst=pConn->Execute("select*fromauthors",NULL,adCmdText);
30
31
//pRst->Open("select*fromauthors",_variant_t((IDispatch*)pConn),adOpenDynamic,adLockOptimistic,adCmdText);
32
33
pCmd->put_ActiveConnection(_variant_t((IDispatch*)pConn));
34
35
pCmd->CommandText=
"select*fromauthors"
;
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_errore)
56
57
{
58
59
CStringerrormessage;
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
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: