procedure TForm1.ExportData(SourceTableName, OutputFile: String); var AFile: TextFile; Q1: TQuery; I,J: Longint; RS: String; VA: array of String; begin Q1 := TQuery.Create(nil); try Assignfile(AFile,OutputFile); Rewrite(AFile); //打开输出文件 Q1.SQL.Clear; Q1.SQL.Add('Select * from "'+SourceTableName+'"'); Q1.Open; SetLength(VA,Q1.FieldCount); //设置动态数组长度 ProgressBar1.Max := Q1.RecordCount; for I:=0 to Q1.RecordCount-1 do //从第一条记录到最后一条记录循环 begin RS := ''; for J:=0 to Q1.FieldCount-1 do //从第一个字段到最后一个字段循环 begin case Q1.Fields[J].DataType of ftInteger,ftFloat,ftDate: VA[J] := Q1.Fields[J].AsString; ftString,ftMemo: VA[J] := '"'+Q1.Fields[J].AsString+'"'; end; if J = Q1.FieldCount-1 then VA[J] := VA[J] else VA[J] := VA[J]+','; RS := RS+VA[J]; end; Writeln(AFile,RS); //写入行 Q1.Next; ProgressBar1.StepIt; //画进度条 Application.ProcessMessages; end; Closefile(AFile); ProgressBar1.Position := 0; MessageBox(Handle,'完成!','',MB_OK); finally Q1.Close; Q1.Free; end; end;
当然也可以根据数据库结构定义一个记录类型,如 PTableRecord = TTableRecord^ TTableRecord = Record field1: type field2: type …… end; 再声明一个文件 var myfile: file of TableRecord p: PTableRecord; 将数据库记录读到P中然后添加到文件中
var AFile: TextFile;
Q1: TQuery;
I,J: Longint;
RS: String;
VA: array of String;
begin
Q1 := TQuery.Create(nil);
try
Assignfile(AFile,OutputFile);
Rewrite(AFile); //打开输出文件 Q1.SQL.Clear;
Q1.SQL.Add('Select * from "'+SourceTableName+'"');
Q1.Open;
SetLength(VA,Q1.FieldCount); //设置动态数组长度
ProgressBar1.Max := Q1.RecordCount;
for I:=0 to Q1.RecordCount-1 do //从第一条记录到最后一条记录循环
begin
RS := '';
for J:=0 to Q1.FieldCount-1 do //从第一个字段到最后一个字段循环
begin
case Q1.Fields[J].DataType of
ftInteger,ftFloat,ftDate:
VA[J] := Q1.Fields[J].AsString;
ftString,ftMemo:
VA[J] := '"'+Q1.Fields[J].AsString+'"';
end;
if J = Q1.FieldCount-1 then
VA[J] := VA[J]
else VA[J] := VA[J]+',';
RS := RS+VA[J];
end;
Writeln(AFile,RS); //写入行
Q1.Next;
ProgressBar1.StepIt; //画进度条
Application.ProcessMessages;
end;
Closefile(AFile);
ProgressBar1.Position := 0;
MessageBox(Handle,'完成!','',MB_OK);
finally
Q1.Close;
Q1.Free;
end;
end;
PTableRecord = TTableRecord^
TTableRecord = Record
field1: type
field2: type
……
end;
再声明一个文件
var myfile: file of TableRecord
p: PTableRecord;
将数据库记录读到P中然后添加到文件中