WEB开发网
开发学院软件开发VC Ado实现C++对象的存取 阅读

Ado实现C++对象的存取

 2010-02-19 20:33:35 来源:WEB开发网   
核心提示:二、用Ado接口打开数据库BOOL CTestAdoDlg::OpenDb(CString filename){HRESULT hr=S_OK;hr=m_pCon.CreateInstance("ADODB.Connection");if (hr!=S_OK){return FALSE;}try{_

二、用Ado接口打开数据库

BOOL CTestAdoDlg::OpenDb(CString filename)
{
  HRESULT hr=S_OK;
  hr=m_pCon.CreateInstance("ADODB.Connection");
  if (hr!=S_OK)
  {
    return FALSE;
  }
  try
  {
    _bstr_t sCon;
    sCon=_bstr_t(filename); //路径名
    sCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+sCon;
    hr=m_pCon->Open(sCon,"","",adModeUnknown);
    if (hr!=S_OK)
    {
      return FALSE;
    }
    ///////////////////////
    hr=m_pSet.CreateInstance("ADODB.Recordset");
    if (hr!=S_OK)
    {
      return FALSE;
    }
    m_pSet->CursorLocation=adUseClient;
    hr=m_pSet->Open("SELECT * FROM object_table",_variant_t((IDispatch*)m_pCon,TRUE),
      adOpenStatic,adLockOptimistic,adCmdText);
    if (hr!=S_OK)
    {
      return FALSE;
    }
    return TRUE;
    ///////////////////////
  }
  catch(_com_error &e)
  {
    CString errorMessage;
    errorMessage.Format("连接数据库失败!错误信息:%s",e.ErrorMessage());
    return FALSE;
  }
  return FALSE;
}
(注意:在StdAfx.h中要加入:#import "C:\Program Files\Common Files\SYSTEM\ADO\msado15.dll" no_namespace rename("EOF","adoEOF")

来引入ado库,还有在 BOOL CTestAdoApp::InitInstance() 加入 AfxOleInit();///初始化COM库)

三、CLine对象的保存

void CTestAdoDlg::OnButtonSave()
{
  //m_List
  if (!m_bState) return;
  UpdateData();
  try
  {
    m_pSet->AddNew();
    m_pSet->PutCollect("name", _variant_t(m_sName));

    //保存图形对象
    CMemFile memFile;
    CArchive ar(&memFile, CArchive::store);
    m_Line.Serialize(ar);
    ar.Close();

    DWORD dwSize = memFile.GetLength();
    LPBYTE lpInfo = memFile.Detach();

    VARIANT varBLOB;
    SAFEARRAY *psa;
    SAFEARRAYBOUND rgsabound[1];

    rgsabound[0].lLbound = 0;
    rgsabound[0].cElements = dwSize;

    psa = SafeArrayCreate(VT_UI1, 1, rgsabound);
    for (long i = 0; i < (long)dwSize; i++)
    {
      SafeArrayPutElement (psa, &i, lpInfo++);
    }
    varBLOB.vt = VT_ARRAY | VT_UI1;
    varBLOB.parray = psa;
    m_pSet->GetFields()->GetItem("object")->AppendChunk(varBLOB);
    m_pSet->Update();
    m_List.AddString(m_sName);
  }
  catch(_com_error &e)
  {
    CString str=(char *)e.Description();
    MessageBox(str+"\r保存数据库出问题!","提示",MB_OK|MB_ICONWARNING);
    return ;
  }

}

上一页  1 2 3 4  下一页

Tags:Ado 实现 对象

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接