Delphi中的AdoDataSet是支持ADO訪問的主要
組件,它支持從數(shù)據(jù)表直接獲取數(shù)據(jù),支持用SQL語句獲取數(shù)據(jù)。最重要的是,它定義和實現(xiàn)了兩個重要的例程:
PRocedure LoadFromFile(const FileName: WideString);它從文件中加載數(shù)據(jù)集。
procedure SaveToFile(const FileName: String = ''; Format: TPersistFormat = pfADTG);它將數(shù)據(jù)集保存到文件中。Format確定文件中數(shù)據(jù)集的保存格式,可以使用的有pfADTG (Advanced Data Tablegram format)、pf
xml(Extendable Markup Language)。
因此AdoDataSet是實現(xiàn)導(dǎo)入導(dǎo)出的良好的基礎(chǔ)。
1. 數(shù)據(jù)表的導(dǎo)出
導(dǎo)出數(shù)據(jù)表的操作如下:
1)打開數(shù)據(jù)表,設(shè)置需要導(dǎo)出的條件;
2)使用AdoDataSet,調(diào)用SaveToFile導(dǎo)出記錄;
下面是一個導(dǎo)出操作的示例(假定導(dǎo)出指定數(shù)據(jù)表的全部記錄)。
procedure ExportData(strFileName, strTableName: string);
begin
with AdoDataSet1 do
begin
Close;
CommandText := ‘select * from ’ + strTableName;
Open;
SaveToFile(strFileName);
Close;
end;
end;
2.?dāng)?shù)據(jù)表的導(dǎo)入
下面是一個導(dǎo)入操作的示例(假定存在相同主鍵記錄時更新目的表;假定數(shù)據(jù)表為單主鍵字段,且其字段類型為字符串型)。
Procedure ImportData(strFileName, strTableName, strKeyFieldName: string);
begin
with AdoDataSet1 do
begin
Close;
LoadFromFile(strFileName);
First;
While not eof do
begin
StrKeyValue := FieldByName(strKeyFieldName).AsString;
If RecordInDest(strTableName, strKeyFieldName, strKeyValue) then
begin
AdoDataDest.Close;
AdoDataSetDest.CommandText := Format(‘select * from %s where %s=%s’,[strTableName, strKeyFieldName, QuotedStr(strKeyValue)]);
AdoDataSetDest.Open;
AdoDataSetDest.First;
AdoDataSetDest.Edit;
for I:=0 to FieldList.Count-1 do
AdoDataSetDest.Fields[I] := Fields[I];
AdoDataSetDest.Post;
end
else // 添加記錄
begin
AdoDataDest.Close;
AdoDataSetDest.CommandText := Format(‘select * from %s where 1=0’,[strTableName]); // 獲取字段列表
AdoDataSetDest.Open;
AdoDataSetDest.Insert;
for i:=0 to FieldList.Count-1 do
AdoDataSetDest.Fields[i] := Fields[i];
AdoDataSetDest.Post;
end;
Next;
end;
end;
// 判斷指定主鍵值的記錄在表中是否存在
function RecordInDest(strTableName, strKeyFieldName, strKeyValue: string): boolean;
begin
with AdoQuery1 do
begin
Close;
SQL.Clear;
SQL.Add(Format(‘select count(*) from %s where %s=%s, [strTableName, strKeyFieldName, QuotedStr(strKeyValue)]));
Open;
result := Fields[0].AsInteger > 0;
Close;
end;
end;
如果對數(shù)據(jù)表的情況進行進一步的考慮,并結(jié)合更周密的導(dǎo)入導(dǎo)出方案,比如導(dǎo)入指定字段、導(dǎo)入指定字段、導(dǎo)入指定記錄等等,對導(dǎo)入導(dǎo)出過程進行更詳細的控制,就可以實現(xiàn)強大的、通用的數(shù)據(jù)表的導(dǎo)入導(dǎo)出工具。