q308144069
q308144069
2017-08-04 09:31

C++连接SqlServer数据库执行sql语句时出现“对象关闭时,不允许操作。”的错误!

100
  • c++
  • 数据库
  • sql

图片说明

 CoInitialize(NULL);
    //初始化指针
    _ConnectionPtr sqlsq=NULL;
    HRESULT hr=sqlsq.CreateInstance(_uuidof(Connection));
    if (FAILED(hr))
    {
        cout<<"_ConnectionPtr对象指针实例化失败!!"<<endl;
        return 0;
    }
    else
    {
        try{
            _bstr_t strConnection="Driver={sql server};server=127.0.0.1,1433;uid=sa;pwd=123456;database=test;";//初始化链接参数
            sqlsq->Open(strConnection,"","",adModeUnknown);//执行连接
        }
        //发生连接错误
        catch(_com_error &e)
        {
            cout<<e.Description()<<endl;
        }
        _RecordsetPtr m_pRecordset;
        _ConnectionPtr m_pConnection;
        if (FAILED(m_pRecordset.CreateInstance(_uuidof(Recordset))))
        {
            cout<<"记录集对象指针实例化失败!"<<endl;
            return 0;
        }
        try{
            m_pRecordset->Open(_variant_t("TEXT_Table"),_variant_t((IDispatch*)sqlsq),adOpenKeyset,adLockOptimistic,adCmdTable);
            m_pConnection.CreateInstance(_uuidof(Connection));
            //初始化Connertion指针
            m_pRecordset.CreateInstance(_uuidof(Recordset));
            //初始化Recordset指针
            CString strsql="select * from TEXT_Table";

            //在这里出的错
            m_pRecordset=m_pConnection->Execute(_bstr_t(strsql),NULL,adCmdText);

            while (!m_pRecordset->adoEOF)
            {
                CString temp=(TCHAR*)(_bstr_t)m_pRecordset->GetFields()->GetItem("name")->Value;
                cout<<temp<<endl;
                m_pRecordset->MoveNext();
            }
        }
        catch(_com_error &e)
        {
            cout<<e.Description()<<endl;
        }

    }
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐

换一换