How to Store Record Data in a BLOB Field in Delphi

window showing step to Store Record Data in a BLOB Field in Delphi

In Delphi, a record data type is a special kind of user-defined data type. A record is a container for a mixture of related variables of diverse types, referred to as fields, collected into one type.

In database applications, data is stored in fields of various types: integer, string, bit (boolean), etc. While most data can be represented with simple data types, there are situations when you need to store images, rich documents or custom data types in a database.

When this is the case you will use the BLOB (Binary Large Object) data type ("memo", "ntext", "image", etc. - the name of the data type depends on the database you work with).

Record as Blob

Here's how to store (and retrieve) a record (structure) value into a blob field in a database.

TUser = record ...
Suppose you have defined your custom record type as:

 TUser = packed record
   Name : string[50];
   CanAsk : boolean;
   NumberOfQuestions : integer;
end; 

"Record.SaveAsBlob"
To insert a new row (database record) in a database table with a BLOB field named "data", use the following code:

 var
   User : TUser;
   blobF : TBlobField;
   bs : TStream;
begin
   User.Name := edName.Text;
   User.NumberOfQuestions := StrToInt(edNOQ.Text) ;
   User.CanAsk := chkCanAsk.Checked;
   myTable.Insert;
   blobF := myTable.FieldByName('data') as TBlobField;
   bs := myTable.CreateBlobStream(blobF, bmWrite) ;
   try
     bs.Write(User,SizeOf(User)) ;
   finally
     bs.Free;
   end;
end; 

In the code above:

  • "myTable" is the name of the TDataSet component you are using (TTable, TQuery, ADOTable, TClientDataSet, etc).
  • The name of the blob field is "data".
  • The "User" variable (TUser record) is filled using 2 edit boxes ("edName" and "edNOQ")and a check box ("chkCanAsk")
  • The CreateBlobStream method creates a TStream object for writing to the blob field.

    "Record.ReadFromBlob"
    Once you have saved the record (TUser) data to a blob type field, here's how to "transform" binary data to a TUser value:

     var
       User : TUser;
       blobF : TBlobField;
       bs : TStream;
    begin
       if myTable.FieldByName('data').IsBlob then
       begin
         blobF := DataSet.FieldByName('data') as TBlobField;
         bs := myTable.CreateBlobStream(blobF, bmRead) ;
         try
           bs.Read(user,sizeof(TUser)) ;
         finally
           bs.Free;
         end;
       end;
       edName.Text := User.Name;
       edNOQ.Text := IntToStr(User.NumberOfQuestions) ;
       chkCanAsk.Checked := User.CanAsk;
    end; 

    Note: the code above should go inside the "OnAfterScroll" event handler of the myTable dataset.

    That's it. Make sure you download the sample Record2Blob code.