VC++连接SQLServer

/*

*连接SQL

*/

void CMFCSQLDlg::OnButton3()

{

       // TODO: Add your control notification handler code here

       _ConnectionPtr   m_pConnection;

// 在应用程序的InitInstance函数里加入

      if(S_OK!=CoInitialize(NULL))  

      {  

         AfxMessageBox("初始化COM库错误!");

      }else

        {

            AfxMessageBox("初始化COM库成功!");

        }

// 连接数据库:  

HRESULT hr; //返回结果变量

try  

{  

      hr=m_pConnection.CreateInstance("ADODB.Connection"); //创建Connection对象

      if(SUCCEEDED(hr))  

      {  

//hr=m_pConnection->Open("Provider=SQLOLEDB;Server=808644DA83B446C\SQLEXPRESS;Database=ChinabaseSQLServer;UserID=sa;pwd=123","","",adModeUnknown);   //;Integrated Security=SSPI

m_pConnection->Open("Provider=SQLOLEDB.1;Server=808644DA83B446C\\SQLEXPRESS;DATABASE=ChinabaseSQLServer;UID=sa;PWD=123;","","",adModeUnknown);

MessageBox("连接SQL运行成功!","成功",MB_OK);

 

              _CommandPtr m_pCommand;

              _RecordsetPtr m_pRecordset;

              m_pCommand.CreateInstance("ADODB.Command");

 

              _variant_t vNULL;

              vNULL.vt = VT_ERROR;

              vNULL.scode = DISP_E_PARAMNOTFOUND;///定义为无参数

              m_pCommand->ActiveConnection = m_pConnection;///非常关键的一句,将建立的连接赋值给它

              m_pCommand->CommandText = "SELECT * FROM MTables order by tname";///命令字串

              m_pRecordset = m_pCommand->Execute(&vNULL,&vNULL,adCmdText);///执行命令,取得记录集

 

              m_pRecordset->MoveFirst();

              for(;!m_pRecordset->adoEOF;m_pRecordset->MoveNext())

              {

                      // printf(m_pRecordset->GetCollect(("myage")));

                     _variant_t var;

                     var = m_pRecordset->GetCollect(("tname"));

                     if(var.vt!=VT_NULL)

                     {

                      //printf((LPCTSTR)_bstr_t(var));

                      AfxMessageBox((LPCTSTR)_bstr_t(var));

                     }

              }

      }

}

catch(_com_error   e)

{  

      CString   errorMsg;

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

      MessageBox(errorMsg,"错误",MB_OK);

}

}

 

posted @ 2010-05-08 10:59  叮当小马  阅读(7816)  评论(0编辑  收藏  举报