CByteArrayFile - storing objects in databases using DAO






4.42/5 (6 votes)
Mar 18, 2000

75990

2239
A class used to serialize object into a database field
You HongJiang contributed the
CByteArrayFile
class and article, and
Daniel Kaminski contributed the
demonstration
application.
In my project I need to serialize some objects into a database field with DAO. However, I can not find any support for serializing anobject into database field. I had to implemented one by myself.
In this example, I will show you a class named CByteArrayFile
. It is a derived
class of CMemFile
. With this class we can serialize objects into a
CByteArray
object. We can then use DFX_Binary
to transfer
data into a database "long binary" field.
Following is the sample code of how to use the CByteArrayFile
class.
In the class which need to be serialized (such as CSomeClass
):
CSomeClass::TransferDataWithByteArray(CByteArray& byteArray, BOOL bStore) { CByteArrayFile byFile; byFile.SetArray(&byteArray); // attach byteArray with byFile if (bStore) // store object into byteArray { // create CArchive object with CByteArray File CArchive ar( &byFile, CArchive::store); // Call CSomeClass::Serialize function Serialize(ar); ar.Close(); } else // load object from byteArray { CArchive ar( &byFile, CArchive::load); Serialize(ar); // Call CSomeClass::Serialize function ar.Close(); } // important!! detach byteArray with byFile. Or byteArray will be // free with byFile byFile.Detach(); }In the file which used
CDaoRecordset
derived a class such as
CSomeDaoRecordset
CSomeDaoRecordset rs; // rs.m_byteLongField is a CByteArray class CSomeClass object; // 1. Write to record rs.Open(. . .); rs.AddNew(); object.TransferDataWithByteArray(rs.m_byteLongField, TRUE /* store */); . . . rs.Update(); rs.Close(); // 2. Read from record rs.Open(. . .); object.TransferDataWithByteArray(rs.m_byteLongField, FALSE /* load */); ... rs.Close();