MFC:用ADO连接SQLSERVER

1.新建一对话框:Ado,如图所示:控件listbox和button

2.导入ADO库:在stdafx.h中导入该库

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

3.查询按钮代码:

 1 void CAdoDlg::OnBtnQuery() 
 2 {
 3     // TODO: Add your control notification handler code here
 4     CoInitialize(NULL);    //初始化COM库
 5     _ConnectionPtr pConn(__uuidof(Connection));    //定义一个ADO Connection对象:pConn,并初始化
 6     _RecordsetPtr pRst(__uuidof(Recordset));
 7     _CommandPtr pCmd(__uuidof(Command));
 8 
 9     pConn->ConnectionString = "Provider=SQLOLEDB; Server=.; Database=InfoData; uid=sa; pwd=12345678;";    //"="两边不能有空格
10     pConn->Open(pConn->ConnectionString,"","",adConnectUnspecified);
11 
12     //pRst = pConn->Execute("select * from t_check_sn_list",NULL,adCmdText);
13     //pRst->Open("select * from t_check_sn_list",_variant_t((IDispatch*)pConn),adOpenDynamic,adLockOptimistic,adCmdText);
14     pCmd->put_ActiveConnection(_variant_t((IDispatch*)pConn));
15     pCmd->CommandText = "select * from t_check_sn_list";
16     pRst = pCmd->Execute(NULL,NULL,adCmdText);
17     while(!pRst->rsEOF){
18         ((CListBox*)GetDlgItem(IDC_LIST1))->AddString((_bstr_t)pRst->GetCollect("SeqNum"));    //SeqNum为表t_check_sn_list的一列
19             pRst->MoveNext();
20     }
21     pRst->Close();
22     pConn->Close();
23     pCmd.Release();
24     pRst.Release();
25     pConn.Release();
26     CoUninitialize();    //卸载COM库
27 }

成功如图:

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。