MFC存储图片到SQL Server数据库

第一步:建立数据库表,比如:id char,pic image。

第二步:建立MFC单文档应用程序,再添加类CMyRecordset,基类选择CRecordset,导入数据库的刚建立的表。

第三步:在doc.h中加入 CMyRecordset m_pSet。

第四步:在view.h中加入CMyRecordset* pSet。

第五步:在view.cpp中的OnInitialUpdate()加入

            

pSet=&GetDocument()->m_pSet;
            if(pSet->IsOpen())
            pSet->Close();
            pSet->Open();

第六步:存图片

void ****View::OnOpen() 
{
 // TODO: Add your command handler code here
 CFileDialog filedlg(TRUE,NULL,NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"images Files (*.jpg)|*.jpg",this);
 CString path;
 if(filedlg.DoModal()==IDOK)
 {
  path=filedlg.GetPathName();
  CFile file;
  CFileStatus filestatus;
  file.Open(path,CFile::modeRead);
  file.GetStatus(filestatus);
  pSet->AddNew();
  pSet->m_pic.m_dwDataLength=filestatus.m_size;
  HGLOBAL hGlobal = GlobalAlloc(GPTR,filestatus.m_size); 
  pSet->m_pic.m_hData = GlobalLock(hGlobal); 
  file.ReadHuge(pSet->m_pic.m_hData,filestatus.m_size); 
  pSet->m_id=_T("1");
  pSet->SetFieldDirty(NULL); 
  pSet->SetFieldNull(NULL,FALSE);
  pSet->Update();
  GlobalUnlock(hGlobal);
 }
}

第七步:读取图片

void ****View::OnRead() 
{
 // TODO: Add your command handler code here
 CFile file2;
 file2.Open("C://a.jpg",CFile::modeCreate|CFile::modeWrite);
 pSet->MoveFirst();//读第一条记录
 BYTE* content=new BYTE[pSet->m_pic.m_dwDataLength];
 memcpy(content,GlobalLock(pSet->m_pic.m_hData),pSet->m_pic.m_dwDataLength); 
 file2.WriteHuge(content,pSet->m_pic.m_dwDataLength); 
}

http://blog.csdn.net/zhaoweihornets/article/details/5719915

原文地址:https://www.cnblogs.com/wxl845235800/p/7429978.html