Tuesday, March 3, 2020

Storing Record Data in a BLOB Field in Delphi

Storing 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 Heres 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.SaveAsBlobTo 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.ReadFromBlobOnce you have saved the record (TUser) data to a blob type field, heres 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. Thats it. Make sure you download the sample Record2Blob code.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.