Tip: Storing Empty Strings Using CLongBinary and CRecordset
This is a common problem that many developers face when using the CLongBinary class in conjunction with the CRecordset class. To update one of your records in a database table, your code fragment might typically look like this:
rs.m_blongbinaryColumns = 1;
long nBytes = lstrlen(lpszData)
rs.m_longbinary.m_dwDataLength = nBytes;
rs.m_longbinary.m_hData = GlobalAlloc(GHND,nBytes);
void * buffer = _
// Report Error
e -> Delete();
This works perfectly for all of the scenarios except when the input is an empty string. If you pass an empty string to this function, it succeeds but stores a NULL in the database instead of an empty string. This happens because when the Recordset update is invoked, it checks that the length is 0 and then puts a NULL for the corresponding field in the table.
The workaround to store empty strings is to lie and give the length of the string as 1, even if it's 0:
long nBytes = lstrlen(lpszData);
if(nBytes == 0)
nBytes = 1;
// Rest of the code remains the same
This fools the Recordset update so it stores the data— the \0 character—which is an empty string.
CLongBinary is sometimes a pain when used with CRecordset, so make sure you've got the following things configured right when using it:
• Your database table has a primary key defined.
• Your Recordset is a dynaset.
• The CRecordset member variable m_bLongBinaryColumns is set to 1 before editing.