我在使用vc通过ADO访问数据库时,总是连接失败,试了好多次,就是在 OPEN函数那有问题,请高手指教,我是第一次用ADO访问SQL sever 数据库
void CTttDlg::OnOK() 
{
  //添加一个指向Connection对象的指针
  _ConnectionPtr m_pConnection;
//添加一个指向Recordset对象的指针    _RecordsetPtr m_pRecordset;

//初始化OLE/COM库环境
::CoInitialize(NULL);
try{
//创建Connection 对象

m_pConnection.CreateInstance("ADODB.Recordset");
//设置连接字符串,必须是BSTR类型或者_bstr_t类型 _bstr_t strConnect

                 ="Provider=SQLOLEDB.1;Server=VSK7HSNYNAV8RBU;Database=Stock;uid=dbaccess;pwd=dbaccess";

m_pConnection->Open(strConnect,"","",adModeUnknown);
  
}//adModeUnknown
catch(_com_error e){
//显示错误信息
AfxMessageBox("连接数据库失败");
    AfxMessageBox(e.Description());
// exit(0); }//释放环境
// ::CoUninitialize();//关闭OLE/COM库,释放资源
}
/*备注: Server=VSK7HSNYNAV8RBU,是我的服务器名字,Database=Stock;是我的数据库名,uid=dbaccess;pwd=dbaccess是用户名和密码*/

解决方案 »

  1.   

    m_pConnection.CreateInstance( "ADODB.Connection "); 
      

  2.   

    strConn="driver={SQL Server}; Server=%s; DATABASE=%s; UID=%s; PWD=%s", m_server,m_db,m_user, m_pwd
    ::CoInitialize(NULL); // 初始化OLE/COM库环境 
    try
    {
    m_pConn.CreateInstance("ADODB.Connection"); //创建Connection对象
    m_pConn->ConnectionTimeout=5; //设置超时时间为5秒
    m_pConn->Open((_bstr_t)strConn,"", "", adModeUnknown);//连接数据库
    }

    catch(_com_error e)
    {
    CATCH_ERROR;
    return false;
    }
    return true;
      

  3.   

    我想应该将::CoInitialize(NULL);放在最前面,况且m_pConnection.CreateInstance( "ADODB.Recordset "); 
    应该是ADODB.Connection, 用完之后要close,Release。
      

  4.   

    直接再InitInstance 中初始化com库更简单。
     BOOL CPMSApp::InitInstance()
    {
    AfxEnableControlContainer();
    OleInitialize(NULL);
    if(!AfxOleInit())//初始化COM库
    {
    AfxMessageBox(_T("初始化COM库失败。"),MB_OK);
    exit(0);
    }
    // Standard initialization
    // If you are not using these features and wish to reduce the size
    //  of your final executable, you should remove from the following
    //  the specific initialization routines you do not need.#ifdef _AFXDLL
    Enable3dControls(); // Call this when using MFC in a shared DLL
    #else
    Enable3dControlsStatic(); // Call this when linking to MFC statically
    #endif
    CPMSDlg dlg;
    m_pMainWnd = &dlg;
    int nResponse = dlg.DoModal();
    if (nResponse == IDOK)
    {
    // TODO: Place code here to handle when the dialog is
    //  dismissed with OK
    }
    else if (nResponse == IDCANCEL)
    {
    // TODO: Place code here to handle when the dialog is
    //  dismissed with Cancel
    } // Since the dialog has been closed, return FALSE so that we exit the
    //  application, rather than start the application's message pump.
    return FALSE;
    }