【问题标题】:TClientDataSet read Binary field to TStreamTClientDataSet 读取二进制字段到 TStream
【发布时间】:2014-05-06 17:19:22
【问题描述】:

我已经尽我所能尝试了这个,但似乎无法解决这个问题。我正在使用 Delphi XE3 中的 DBExress 编写 REST DataSnap 服务器。

我将数据存储在 MSQL 中的 Binary(384) 字段中,据我所知,二进制与 BLOB/Image 字段相同,因为它都是二进制数据。

当尝试将此数据流式传输到 TStream 时,我收到异常错误并尝试了以下操作

var
STemplate : TStream;
begin
......
Template := TBlobField.Create(cdsBSUserTemplates.FieldByName('bTemplate'));
TBlobField(cdsBSUserTemplates.FieldByName('bTemplate')).SaveToStream(STemplate); //exception
......
end;

我试过了

var
STemplate : TStream;
begin
......
Template := TBlobField.Create(cdsBSUserTemplates.FieldByName('bTemplate'));
STemplate := cdsBSUserTemplates.CreateBlobStream(Template, bmRead); //exception
......
end;

我可以返回值 .AsString,但它是字节,然后我需要尝试修复我从该字段中读取的内容。

知道我还能尝试什么吗?

【问题讨论】:

    标签: sql-server delphi delphi-xe3 dbexpress tclientdataset


    【解决方案1】:

    你工作太辛苦了。 :-)

    您需要正确创建流,然后让字段写入它。

    var
      Output: TMemoryStream;
      Fld: TBlobField;
    begin
      // Use of variable makes it more readable
      Fld := cdsBSUserTemplates.FieldByName('bTemplate') as TBlobField;
    
      Output := TMemoryStream.Create;
      try
        Fld.SaveToStream(Output);
        Output.Position := 0;
        // Do whatever with the output stream
      finally
        Output.Free;
      end;
    end;
    

    在您评论说您可能没有使用TBlobField(在我发布我的答案之前很高兴知道)之后,您可以试试这个(未经测试,因为我显然不'没有你的数据):

    var
      Output: TMemoryStream;
      Fld: TField;
      Bytes: TArray<Byte>;
    begin
      Fld := ADOQuery1.FieldByName('bTemplate');
      Output := TMemoryStream.Create;
      try
        if Fld.IsBlob then
          TBlobField(Fld).SaveToStream(Output)
        else
        begin
          Fld.GetData(Bytes);
          Output.WriteData(Bytes, Length(Bytes));
        end;
        // Do whatever with output
      finally
        Output.Free;
      end;
    end;
    

    【讨论】:

    • Template := cdsBSUserTemplates.FieldByName('bTemplate') as TBlobField - 我在此处收到 Invalid Type cast 错误。我确信 TSQLQuery 或 TClientDataSet 没有该字段的正确数据类型。会调查的。
    • 当我检查字段类型时它是 TVarByteField 如果这有帮助
    • @StefanDeBeer 你应该在问这个问题之前解决这个问题
    猜你喜欢
    • 1970-01-01
    • 2021-11-09
    • 2011-07-27
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多