firedac数据集和字符串之间相互转换
/// <author>cxg 2018-12-20</author> unit DatasetString; interface uses
System.NetEncoding, FireDAC.Stan.Intf, System.ZLib, System.Classes, FireDAC.Comp.Client,
System.SysUtils; function DataSetToString(const ADataSet: TFDAdaptedDataSet): string; function MemTableFromString(const AValue: string): TFDMemTable; implementation function DataSetToString(const ADataSet: TFDAdaptedDataSet): string;
var
LBinary64: string;
LMemoryStream: TMemoryStream;
LStringStream: TStringStream;
LDstStream: TMemoryStream;
Zipper: TZCompressionStream;
begin
LDstStream := TMemoryStream.Create;
try
LMemoryStream := TMemoryStream.Create;
try
ADataSet.SaveToStream(LMemoryStream, TFDStorageFormat.sfBinary);
LMemoryStream.Seek(0, TSeekOrigin.soBeginning);
Zipper := TZCompressionStream.Create(clDefault, LDstStream);
try
Zipper.CopyFrom(LMemoryStream, LMemoryStream.Size);
finally
Zipper.Free;
end;
finally
LMemoryStream.Free;
end;
LDstStream.Seek(0, TSeekOrigin.soBeginning); LStringStream := TStringStream.Create;
try
TNetEncoding.Base64.Encode(LDstStream, LStringStream);
LBinary64 := LStringStream.DataString;
finally
LStringStream.Free;
end;
finally
LDstStream.Free;
end;
Result := LBinary64;
end; function MemTableFromString(const AValue: string): TFDMemTable;
var
LMemTable: TFDMemTable;
LStringStream: TStringStream;
LMemoryStream: TMemoryStream;
LOrgStream: TMemoryStream;
Unzipper: TZDecompressionStream;
begin
LMemTable := TFDMemTable.Create(nil);
LMemoryStream := TMemoryStream.Create;
try
LStringStream := TStringStream.Create(AValue);
try
LOrgStream := TMemoryStream.Create;
try
TNetEncoding.Base64.Decode(LStringStream, LOrgStream);
LOrgStream.Seek(0, TSeekOrigin.soBeginning);
Unzipper := TZDecompressionStream.Create(LOrgStream);
try
LMemoryStream.CopyFrom(Unzipper, Unzipper.Size);
finally
Unzipper.Free;
end;
LMemoryStream.Seek(0, TSeekOrigin.soBeginning);
finally
LOrgStream.Free;
end;
finally
LStringStream.Free;
end;
LMemTable.LoadFromStream(LMemoryStream, TFDStorageFormat.sfBinary);
finally
LMemoryStream.Free;
end;
Result := LMemTable;
end; end.