How to load a binary file(.bin) of size 6 MB in a varbinary(MAX) column of SQL Server 2005 database
- by Feroz Khan
How to load a binary file(.bin) of size 6 MB in a varbinary(MAX) column of SQL Server 2005 database using ADO in vc++ application.
This is the code I am using to load the file which I used to load a .bmp file
BOOL CSaveView::PutECGInDB(CString strFilePath, FieldPtr pFileData)
{
//Open File
CFile fileImage;
CFileStatus fileStatus;
fileImage.Open(strFilePath,CFile::modeRead);
fileImage.GetStatus(fileStatus);
//Alocating memory for data
ULONG nBytes = (ULONG)fileStatus.m_size;
HGLOBAL hGlobal = GlobalAlloc(GPTR,nBytes);
LPVOID lpData = GlobalLock(hGlobal);
//Putting data into file
fileImage.Read(lpData,nBytes);
HRESULT hr;
_variant_t varChunk;
long lngOffset = 0;
UCHAR chData;
SAFEARRAY FAR *psa = NULL;
SAFEARRAYBOUND rgsabound[1];
try
{
//Create a safe array to store the BYTES
rgsabound[0].lLbound = 0;
rgsabound[0].cElements = nBytes;
psa = SafeArrayCreate(VT_UI1,1,rgsabound);
while(lngOffset<(long)nBytes)
{
chData = ((UCHAR*)lpData)[lngOffset];
hr = SafeArrayPutElement(psa,&lngOffset,&chData);
if(hr != S_OK)
{
return false;
}
lngOffset++;
}
lngOffset = 0;
//Assign the safe array to a varient
varChunk.vt = VT_ARRAY|VT_UI1;
varChunk.parray = psa;
hr = pFileData-AppendChunk(varChunk);
if(hr != S_OK)
{
return false;
}
}
catch(_com_error &e)
{
//get info from _com_error
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
_bstr_t bstrErrorMessage(e.ErrorMessage());
_bstr_t bstrErrorCode(e.Error());
TRACE("Exception thrown for classes generated by #import");
TRACE("\tCode= %08lx\n",(LPCSTR)bstrErrorCode);
TRACE("\tCode Meaning = %s\n",(LPCSTR)bstrErrorMessage);
TRACE("\tSource = %s\n",(LPCSTR)bstrSource);
TRACE("\tDescription = %s\n",(LPCSTR)bstrDescription);
}
catch(...)
{
TRACE("Unhandle Exception");
}
//Free Memory
GlobalUnlock(lpData);
return true;
}
But when I read the same file using Getchunk funcion it gives me all 0,s but the size of the file I get is same as the one uploaded.
Your help will be highly appreciated.
Thanks in advance.