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") //最好加在stdafx.h最后一行

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     try{

 9     //pConn->ConnectionString = "Provider=SQLOLEDB; Server=.; Database=InfoData; uid=sa; pwd=12345678;";    //"="两边不能有空格

10     pConn->ConnectionString = "Provider=SQLOLEDB.1; User ID=sa; Password=12345678; Initial Catalog=Stock; Data Source=.;";

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

12     }

13     catch(_com_error e)///捕捉异常 

14     { 

15         CString errormessage; 

16         errormessage.Format("连接数据库失败!\r\n错误信息:%s",e.ErrorMessage()); 

17         AfxMessageBox(errormessage);///显示错误信息 

18     } 

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

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

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

22     //pCmd->CommandText = "select * from t_check_sn_list";

23     pCmd->CommandText = "select * from Users";

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

25     while(!pRst->rsEOF){

26         ((CListBox*)GetDlgItem(IDC_LIST1))->AddString((_bstr_t)pRst->GetCollect("Pwd"));    //SeqNum为表t_check_sn_list的一列

27             pRst->MoveNext();

28     }

29     pRst->Close();

30     pConn->Close();

31     pCmd.Release();

32     pRst.Release();

33     pConn.Release();

34     CoUninitialize();    //卸载COM库

35 }

 

成功如图:

你可能感兴趣的:(sqlserver)