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;