我在用VC做一个程序,需要访问数据库
我在Stdafx.h中加入了:
#import "c:\program files\common files\system\ado\msado15.dll"no_namespaces rename("EOF","adoEOF")
在要用到数据库的地方:
ADODB::_ConnectionPtr m_pConnection;
if (FAILED(m_pConnection.CreateInstance("ADODB.Connection")))
{
        AfxMessageBox("Create Instance failed!");
        return;
 }这是在网上找到的代码,但是FAILED函数只会返回false,后面的代码无法执行,是哪里出错了呢

解决方案 »

  1.   

    // ADOConn.cpp: implementation of the ADOConn class.
    //
    //////////////////////////////////////////////////////////////////////#include "stdafx.h"
    #include "HrSys.h"
    #include "ADOConn.h"#ifdef _DEBUG
    #undef THIS_FILE
    static char THIS_FILE[]=__FILE__;
    #define new DEBUG_NEW
    #endif//////////////////////////////////////////////////////////////////////
    // Construction/Destruction
    //////////////////////////////////////////////////////////////////////
    void ADOConn::OnInitADOConn()
    {
    //初始化OLE/COM库环境
    ::CoInitialize(NULL);
    try
    {
    //创建Connection对象
    m_pConnection.CreateInstance("ADODB.Recordset");
    //设置连接字符串,必须是BSTR型或者_bstr_t类型
    _bstr_t strConnect = "Provider = SQLOLEDB;Server = ntserver;Database = HrSys;uid = sa;pwd = sa;";
    m_pConnection->Open(strConnect,"","",adModeUnknown);
    }
    //捕捉异常
    catch(_com_error e)
    {
    //显示错误信息
    AfxMessageBox(e.Description());
    }
    }_RecordsetPtr& ADOConn::GetRecordSet(_bstr_t bstrSQL)
    {
    try
    {
    //连接数据库,如果Connection对象为空,则重新连接数据库
    if(m_pConnection == NULL)
    OnInitADOConn();
    //创建记录集对象
    m_pRecordset.CreateInstance(_uuidof(Recordset));
    //取得表中记录
    m_pRecordset->Open( bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
    }
    //捕捉异常
    catch(_com_error e)
    {
    //显示错误信息
    AfxMessageBox(e.Description());
    }
    //返回记录集
    return m_pRecordset;
    }bool ADOConn::ExecuteSQL(_bstr_t bstrSQL)
    {
    try
    {
    //是否已经连接数据库
    if(m_pConnection == NULL)
    OnInitDBConnect();
    m_pConnection->Execute(bstrSQL,NULL,adCmdText);
    return true;
    }
    catch(_com_error e)
    {
    AfxMessageBox(e.Description());
    return false;
    }
    }void ADOConn::ExitConnect()
    {
    //关闭记录集和连接
    if(m_pRecordset != NULL)
    m_pRecordset->Close();
    m_pConnection->Close();
    //释放环境
    ::CoUninitialize();
    }
    ADOConn::ADOConn()
    {}ADOConn::~ADOConn()
    {}
      

  2.   

    初始化了,在应用程序里
    if(!AfxOleInit())//这就是初始化COM库
    {
    AfxMessageBox(“OLE初始化出错!”);
    return FALSE;

      

  3.   

    但是FAILED函数只会返回false,负负得正,岂不是没有问题?