2011. április 29., péntek

How to read a TMemoField or TBlobField into a string


Problem/Question/Abstract:

I'd like to do something like this (myquery is a TQuery):

myquery.first;
while not myquery.eof do
begin
  writeln(myquery.fieldbyname('description').asstring);
  myquery.next;
end;

But since the field "description" is of type memo, I get this error : "invalid blob handle in record buffer".

Answer:

The contents of complex field types like BLOB and memo are not intended to be retrieved via the TField.AsString property, designed for use with the simple field type CHAR. There are other ways, though, to retrieve the memo data into a String variable.

One way is to use the TMemoField.Text property. For example:

{ ... }
if (Myquery.FieldByName('Description') is TMemoField) then
  StrVar := TMemoField(Myquery.FieldByName('Description')).Text
else
  StrVar := Myquery.FieldByName('Description').AsString;

Another way would be to use the Assign method of a an already-existing string list object. Parse the string list object to get individual lines. After creating a string list object (here named SL):

{ ... }
if (Myquery.FieldByName('Description') is TMemoField) then
begin
  SL.Assign(TMemoField(Myquery.FieldByName('Description')));
  {... parse string list }
end
else
  StrVar := Myquery.FieldByName('Description').AsString;

Still another way would be to extract the memo contents using a TBlobStream object. The TBlobStream.Read method will copy the contents from a memo field into a PChar (or equivalent) buffer, which can then be converted to a String value.

{ ... }
if (Myquery.FieldByName('Description') is TMemoField) then
begin
  BS := TBlobStream.Create(TMemoField(Myquery.FieldByName('Description')), bmRead);
  SizeOfMemoContents := BS.Size;
  YourPCharBuffer := AllocMem(SizeOfMemoContents + 1);
  BS.Read(YourPCharBuffer, SizeOfMemoContents);
  StrVar := StrPas(YourPCharBuffer);
  BS.Free;
  FreeMem(YourPCharBuffer);
  { do something with the retrieved string };
end
else
  { react to a non-memo field };

Nincsenek megjegyzések:

Megjegyzés küldése