[原创]VC往access中插入二进制数据

0.创建数据库.把其中的二进制字段设为OLE对象.

1.连接数据库:

_RecordsetPtr m_pRecordset;

try
{
   m_pRecordset.CreateInstance("ADODB.Recordset");
   m_pRecordset->Open("SELECT * FROM myTable ORDER BY id",_variant_t((IDispatch*)theApp.m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
}

catch(_com_error e)///捕捉异常
{
   AfxMessageBox("读取数据库失败!");///显示错误信息
}

2.插入二进制数据

    BYTE *pBuf = pBuffer;     ///下面这一大段是把pBuffer里的二进制数据放到库中
    VARIANT    varHaha;
    SAFEARRAY   *psa;
    SAFEARRAYBOUND rgsabound[1];
   
    m_pRecordset->AddNew();
   
    if(pBuf)
    {   
     rgsabound[0].lLbound = 0;
     rgsabound[0].cElements = nSize;
     psa = SafeArrayCreate(VT_UI1, 1, rgsabound);
     for (long i = 0; i < (long)nSize; i++)
      SafeArrayPutElement (psa, &i, pBuf++);
     varHaha.vt = VT_ARRAY | VT_UI1;
     varHaha.parray = psa;
     m_pRecordset->GetFields()->GetItem("HahaData")->AppendChunk(varHaha);
    }
    m_pRecordset->Update();
   
    // +----------------------------------------------
    delete [] pBuffer;     //删掉堆上申请的那一块内存
    pBuf=0;                //以防二次乱用

3.读取二进制数据

   long nSize = m_pRecordset->GetFields()->GetItem("HahaData")->ActualSize;
   if(nSize > 0)
   {
    _variant_t varHaha;
    varHaha= m_pRecordset->GetFields()->GetItem("HahaData")->GetChunk(nSize);
    if(varHaha.vt == (VT_ARRAY | VT_UI1))
    {
     if(BYTE *pBuffer = new BYTE [nSize+1])   ///重新申请必要的存储空间
     {
     memset(pBuffer,0,nSize+1);
      char *pBuf = NULL;
      SafeArrayAccessData(varHaha.parray,(void **)&pBuf);
      memcpy(pBuffer,pBuf,nSize);     ///复制数据到缓冲区
      SafeArrayUnaccessData (varHaha.parray);
      // nSize为数据长度
       //pBuffer为数据头
  delete [] pBuffer;
      pBuf=null;
}


你可能感兴趣的:([原创]VC往access中插入二进制数据)