1. 程式人生 > >MFC使用ODBC把圖片寫入blob欄位

MFC使用ODBC把圖片寫入blob欄位

第一,新增一個基於CRecordSet的類為CMyRecordset1,設定如下圖片。

第二,讀圖片檔案,寫入blob欄位

CDatabase db;

//db.Open(NULL, FALSE, FALSE, "ODBC;DSN=kdmysql;UID=root;PWD=zrsoft");
db.Open(NULL,FALSE,FALSE,"ODBC;DSN=kdmysql;UID=root;PWD=zrsoft");


CMyRecordset1 db_set(&db);
CString sSql;
sSql = "SELECT * FROM studentphoto";
db_set.Open(CRecordset::snapshot,sSql);
db_set.AddNew();
//db.ExecuteSQL("insert into studentphoto VALUES('2017117161823704','6410020001',NULL)");
//db_set.Update();
db_set.m_testflag= "2017117161823705";
db_set.m_ExamineeID= "2017117161823705";
CFile file1;
file1.Open("E:\\practice\\TestODBC\\Debug\\6410020001.jpg",CFile::modeRead|CFile::typeBinary);//開啟指定檔案
db_set.m_photo.m_dwDataLength = file1.GetLength();//m_blobfile為資料庫中blob欄位由classwizard對映過來的CLongBinary欄位
HGLOBAL hGlobal = GlobalAlloc(GPTR,db_set.m_photo.m_dwDataLength);
db_set.m_photo.m_hData = GlobalLock(hGlobal);
file1.Read(db_set.m_photo.m_hData,db_set.m_photo.m_dwDataLength);
db_set.SetFieldDirty(&db_set.m_photo,true);
db_set.SetFieldNull(&db_set.m_photo,false);
GlobalUnlock(hGlobal );
db_set.Update();
db_set.Close();

file1.Close();

第三,讀出blob欄位

CDatabase db;
db.Open(NULL,FALSE,FALSE,"ODBC;DSN=kdmysql;UID=root;PWD=zrsoft");

CRecordset rstestset( &db );
CString TestSet;
rstestset.Open( CRecordset::forwardOnly, "select * from studentphoto where testflag = '2017117161823705' and ExamineeID = '2017117161823705'");
if (rstestset.IsEOF())
{
rstestset.Close();
db.Close();
MessageBox("dfdgfdfg","系統提示:",MB_OK);
return ;
}
while (!rstestset.IsEOF())
{
//rstestset.GetFieldValue("TestSet", TestSet);
//rstestset.MoveNext();

CString photo;
CDBVariant CDBVariantphoto;
rstestset.GetFieldValue("photo",CDBVariantphoto);
int photoBuffLen=(int)CDBVariantphoto.m_pbinary->m_dwDataLength;
if((int)CDBVariantphoto.m_pbinary->m_dwDataLength>0)
{
LPSTR phototemp = (LPSTR)GlobalLock(CDBVariantphoto.m_pbinary->m_hData);
//AfxMessageBox(MarkLogtemp);

GlobalUnlock(CDBVariantphoto.m_pbinary->m_hData);
//
CString fileName;
fileName = "E:\\practice\\TestODBC\\";
fileName = fileName + "2017117161823705.jpg";
//m_FilePath.GetWindowText(fileName);
if ((access(fileName, 0)) != 0)
{
CFile file;
if (file.Open(fileName, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary) == FALSE)
{
}
else
{
file.Write(phototemp,photoBuffLen);
file.Flush(); 
file.Close();
}
}
}
}
rstestset.Close();