The Unofficial Newsletter of Delphi
Users - by Robert Vivrette
Archiving Data in TTables and TQueries
Matt Hamilton - mhamilton@bunge.com.au
I've used this in my own projects a few times, and I thought it was
worth sharing. It is a nice method to archive your database.
Often it is necessary to put in place some sort of backup or archive
procedure. If you are unlucky and don't have 3rd-party backup programs,
then you might want to build it into your app. I have done this in several
apps by copying the necessary data to "CSV" (comma separated value) files.
Here is the idea: You collate all the fields you want to save into a
query, then write the entire query off to a CSV file. At some later date
you can 'pipe' the data back in either by using a TBatchMove component,
or simply reversing the technique shown here.
Anyway, the code:
procedure TForm1.ArchiveToFile(AFilename: string);
var
F: TextFile;
FieldStrings: TStringList;
i: Integer;
begin
{ Open the file to append data to, creating
if necessary }
AssignFile(F, AFilename);
if FileExists(AFilename) then Append(F)
else Rewrite(F);
{ ArchiveQry is the TQuery with all
the info to archive }
with ArchiveQry do
begin
Open;
try
{ We use a TStringList for its nifty "CommaText" property }
FieldStrings := TStringList.Create;
try
First;
while not Eof do
begin
FieldStrings.Clear;
for i := 0 to FieldCount - 1 do
FieldStrings.Add(Fields[i].AsString);
WriteLn(F, FieldStrings.CommaText);
Next;
end;
finally
FieldStrings.Free;
end;
finally
Close;
end;
end;
CloseFile(F);
end;
And there you have it! This procedure copies all the data in ArchiveQry
to a file whose name is specified in the parameter AFilename. After you
have copied it out, you could prompt the user to delete the real data,
or flag it as archived, or whatever.
Cheers!