Login


CONTENT
View Current Issue
View Past Issues
Free Articles
Source Code
World's Best Authors
Site Search
MARKETPLACE
Online Store
CD-ROM Products
COMMUNITY
User Groups
Visual C++ Links
Calendar of Events
CAREERS
Job Bank
Salary Survey Results
CONTACT US
Contact Information
Advertising
Pinnacle Publishing Home
Pinnacle Publishing Home


Tip: Storing Empty Strings Using CLongBinary and CRecordset

Sunil B.G.

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:

 UpdateMyData(LPCTSTR lpszData)
{
CMyRecordset rs(&g_myDB);

try
{
rs.m_blongbinaryColumns = 1;
rs.Open();
rs.Edit();

if(rs.m_longbinary.m_hData)
GlobalFree(rs.m_longbinary.m_hData);

long nBytes = lstrlen(lpszData)
rs.m_longbinary.m_dwDataLength = nBytes;
rs.m_longbinary.m_hData = GlobalAlloc(GHND,nBytes);
void * buffer = _
GlobalLock(rs.m_longbinary.m_hData);
memcpy(buffer,lpszContent, sizeof(BYTE)*nBytes);
GlobalUnlock(rs.m_longbinary.m_hData);

rs.SetFieldNull(&rs.m_longbinary, FALSE);
rs.SetFieldDirty(&rs.m_longbinary, TRUE);
rs.Update();
}
catch(CDBException *e)
{
// 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.


Click here to learn more about Sunil BG
 

 

To Contact Customer service: custserv@pinpub.com or call 1-800-788-1900
Copyright © 2001 Pinnacle Publishing, Inc. All Rights Reserved.