请哪位大侠指点一下,最好能提供例程!

解决方案 »

  1.   

    HRESULT hr;
    _bstr_t source("Driver={SQL Server};Server=127.0.0.1;Uid=yourid;Pwd=yourpw;Database=database;");
        try
    {
    ///创建Connection对象
    hr = m_connection.CreateInstance(_uuidof(Connection));
            if(SUCCEEDED(hr))
            ///连接数据库
    hr = m_connection->Open(source,"","",adModeUnknown);
              } 
       catch(_com_error &e)
    ........
      

  2.   

    1.COM库的初始化
    BOOL CADOTest1App::InitInstance()
      {
      AfxOleInit();
      ...... 2.用#import指令引入ADO类型库
    在stdafx.h中加入如下语句:(stdafx.h这个文件哪里可以找到?你可以在FileView中的Header Files里找到)
    #import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
    几点说明:
    (1) 您的环境中msado15.dll不一定在这个目录下,请按实际情况修改
    (2) 在编译的时候肯能会出现如下警告,对此微软在MSDN中作了说明,并建议我们不要理会这个警告。
    msado15.tlh(405) : warning C4146: unary minus operator applied to unsigned type, result still unsigned 3.创建Connection对象并连接数据库
    首先我们需要添加一个指向Connection对象的指针:
    _ConnectionPtr m_pConnection;
    下面的代码演示了如何创建Connection对象实例及如何连接数据库并进行异常捕捉。
    BOOL CADOTest1Dlg::OnInitDialog()
      {
      CDialog::OnInitDialog();
      HRESULT hr;
      try
      {
      hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象
      if(SUCCEEDED(hr))
      {
      hr = m_pConnection->Open("Provider=OLEDBSQL;Data Source=test.mdb","","",adModeUnknown}
      }
      catch(_com_error e)///捕捉异常
      {
      CString errormessage;
      errormessage.Format("连接数据库失败!\r\n错误信息:%s",e.ErrorMessage());
      AfxMessageBox(errormessage);///显示错误信息
      }