Delphi:TMemoryStream类--二进制大对象与数据库的交互

Q:如何将一个大的二进制数组保存到数据库,并从数据库再次取回到数组?
A:使用TMemoryStream类对象,使用内存流对象的 WriteBuffer/ReadBuffer方法和数据库BLOB字段对象的SaveToStream/WriteFromStream方法。以下是我 做的一个例子,Form1只有一个按钮,但是要uses DataModule2;DataModule2里包含一个ADOTable1,指向一个只有两个字段的表,一个字段是序号索引(可以让Access自动 生成),另一个字段是BLOB类型,记得要对这个表生成字段域变量(右键点击ADOTable1-->Fiels Editor...)。

procedure TForm1.Button1Click(Sender: TObject);
var
  SourceString: Array[0..1023] of byte;//byte数组
  DesString: Array[0..1023] of byte;//byte数组
  MemoryStream,MemoryStream2 : TMemoryStream;
  i:integer;
begin
  for i:=Low(SourceString) to High(SourceString) do
  begin
     SourceString[i]:=i;
  end;
   MemoryStream := TMemoryStream.Create;
  MemoryStream2:= TMemoryStream.Create;
  try
    // Write the string to the stream. We want to write from SourceString's
    // data, starting at a pointer to SourceString (this returns a pointer to
    // the first character), dereferenced (this gives the actual character).

    //MemoryStream.WriteBuffer(Pointer(SourceString)^, Length(SourceString));//String写到内存流
    MemoryStream.WriteBuffer(SourceString, Length(SourceString));//String写到内存流
    MemoryStream.Position := 0; // Go back to the start of the stream
    //SetLength(SourceString, MemoryStream.Size); // Set the length, so we have space to read into
    MemoryStream.ReadBuffer(DesString, MemoryStream.Size);//读内存流到字符串 Read it back in to make sure it worked.
    for i:=0 to Length(DesString)-1 do
    Caption :=Caption+','+ inttostr(DesString[i]);

    //ok,from here we can use MemoryStream to save into DB using LoadFromStream Method.
    //使用
    DataModule2.ADOTable1.Open;
    DataModule2.ADOTable1.Edit;
    DataModule2.ADOTable1.Append;
    //从内存流到数据库ADOTable1BinaryData represent a Table's Blob field.
    DataModule2.ADOTable1BinaryData.LoadFromStream(MemoryStream);

    DataModule2.ADOTable1.First;
    DataModule2.ADOTable1BinaryData.SaveToStream(MemoryStream2);//从数据库到内存流2
    MemoryStream2.Position :=0;
    MemoryStream2.ReadBuffer(DesString, MemoryStream2.Size); //从内存流2到 Byte数组DesString
    Label1.Caption :='';
    for i:=0 to Length(DesString)-1 do
    //inttostr:Byte不是 integer,但是我不知道有没有Bytetostr这样的函数,先就凑合着inttostr用吧。
    Label1.Caption :=Label1.caption+','+ inttostr(DesString[i]);

  finally
    MemoryStream.Free;
    MemoryStream2.Free;
  end;

end;


FROM: http://blog.csdn.net/yueyahe/archive/2006/04/19/669418.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值