種用ADO從文本文件中導入數據庫的兩種方法比較

我用的這兩種方法,不管是哪一種,大體原理上都是打開文本,然後一行行讀出,再根據分隔符拆分字段,然後再用ADO來一條條記錄插入數據庫中,但採用的ADO的方式不同,第一種用普通的ADOQUERY來操作,第二種則採用ADO的原生對象來操作,但在速度上是明顯後一種佔優的,且是很大的優勢,原因我說不來,但認爲是個不錯的方法,雖然導入文本還有別的很好的方法,例如採用SQLSERVER的DTS等。但這些我還沒做過嘗試,就暫不說了。
1、
 if dlgOpendatain.Execute then
  begin
    datapath := dlgOpendatain.FileName; //取得文件路徑
    Filepath := ExtractFileName(datapath); //取得文件名
    AssignFile(TeFile1, datapath); //將文件變量與文件關聯
    Reset(TeFile1); //以讀寫方式打開類型文件和無類型文件
    try
      j := 0;
      while not Eof(TeFile1) do
      begin
        application.ProcessMessages;
        Readln(TeFile1, str); //一行一行的讀文件,str爲一行的字符串
        recordstr := str;
        inc(j);
        i := 0;
        while pos(#9, recordstr) > 0 do //#9是tab分隔符
        begin
          str := Copy(recordstr, 1, Pos(#9, recordstr) - 1);
          case i of
            0:str1 := str;
            1:str2 := str;
          end;
          i := i + 1;
          recordStr := copy(recordstr, (Pos(#9, recordstr) + 1),
            length(recordstr));
          if i = 2 then
            str4 := trim(uppercase(recordStr));
        end;
        ADOQuery1.Close;
    ADOQuery1.SQL.Clear;
        ADOQuery1.SQL.TEXT:='INSERT INTO S1,S2,S3 VALUES('+''''+
             str1''''+','+''''+str2+''''+','+''''+str3+''''+')';
        ADOQuery1.Prepare;
        ADOQuery1.ExecSQL ;
      end;
      MessageBox(GetactiveWindow(), '當前導入數據完畢!', '提示',
        MB_OK + mb_iconexclamation);
    except
      CloseFile(TeFile1);
    end;
  end;
2、
按下面的方法,四萬條記錄全部導入ACCESS,直接從文本中裝載23.90秒,當我將文本裝載到MEMO1中的時候,八萬條記錄全部導入ACCESS也不過四十一秒。
unit Unit1;

interface

uses
  Windows,
  Messages,
  SysUtils,
  Variants,
  Classes,
  Graphics,
  Controls,
  Forms,
  Dialogs,
  StdCtrls,
  ComCtrls,
  Gauges,
  DB,
  ADODB,
  ComObj,
  ADOInt;
type
  TStrArray = array[1..9] of string;
type
  TForm1 = class(TForm)
    Button1: TButton;
    OpenDialog1: TOpenDialog;
    StatusBar1: TStatusBar;
    Gauge1: TGauge;
    ADOConnection: TADOConnection;
    Label1: TLabel;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1             : TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
const
  TabChar           = #32;              //定義空格鍵
var
  i, j              : integer;
  D1                : Real;
  TeFile1           : TextFile;
  datapath, Filepath, str: string;
  dd                : TStrArray;
  AdoRecordSet      : variant;
  FConnectionObject : _Connection;
begin
  AdoRecordSet := CreateOleObject('ADODB.RecordSet');
  ADOConnection.Connected := True;
  FConnectionObject := ADOConnection.ConnectionObject;
  AdoRecordSet.CursorLocation := clUseClient;
  AdoRecordSet.open('select *  from abcdefg where 1=2', FConnectionObject,
    adOpenStatic, adLockOptimistic, AdCmdText); //寫數據庫
  try
    OpenDialog1.Title := '請選擇要打開的文件';
    OpenDialog1.Filter := '數據文件(*.txt)|*.txt';
    if OpenDialog1.Execute then
    begin
      DataPath := OpenDialog1.FileName; //取得文件路徑
      Filepath := ExtractFileName(DataPath); //取得文件名
      //      Memo1.Lines.Clear;
      //      Memo1.Lines.LoadFromFile(DataPath); //.LoadFromStream(ms2);
      AssignFile(TeFile1, DataPath);    //將文件變量與文件關聯
      Reset(TeFile1);                   //以讀寫方式打開類型文件和無類型文件
      statusbar1.Panels[1].Text := FormatDateTime('hh:mm:ss', now()); //開始時間
      //Gauge1.MaxValue:=Memo1.Lines.Count;
      D1 := Now;
      try
        //        for i := 0 to Memo1.Lines.Count do
        while not Eof(TeFile1) do
        begin
          Application.ProcessMessages;
          Readln(TeFile1, str);           //一行一行的讀文件,str爲一行的字符串
          statusbar1.Panels[3].Text := str;
          //str := Memo1.Lines[i];
          j := 1;
          while pos(TabChar, str) > 0 do
          begin
            dd[j] := Copy(str, 1, pos(TabChar, str));
            Delete(str, 1, Pos(TabChar, str) + 1);
            Str := TRIM(Str);
            Inc(j);
          end;
          DD[9] := str;
          AdoRecordSet.AddNew;
          try
            AdoRecordSet.fields[1].value := DD[1];
            AdoRecordSet.fields[2].value := DD[2];
            AdoRecordSet.fields[3].value := DD[3];
            AdoRecordSet.fields[4].value := DD[4];
            AdoRecordSet.fields[5].value := DD[5];
            AdoRecordSet.fields[6].value := DD[6];
            AdoRecordSet.fields[7].value := DD[7];
            AdoRecordSet.fields[8].value := DD[8];
            AdoRecordSet.fields[9].value := DD[9];
            AdoRecordSet.Update;
          except

          end;
          Inc(i);
          //Gauge1.Progress:=Gauge1.Progress + 1;
          Label1.Caption:=IntToStr(i);
        end;
        statusbar1.Panels[2].Text := FormatDateTime('hh:mm:ss', now());  //結束時間
        statusbar1.Panels[0].Text := '總用時:  ' + Floattostr((NOW - D1) * 24 *
          60 * 60);
        MessageBox(GetactiveWindow(), '當前導入數據完畢!', '提示',
          MB_OK + mb_iconexclamation);
      except
        CloseFile(TeFile1);
      end;
    end;
  finally
    AdoRecordSet.Close;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var                                     //聯接ACCESS數據庫的方法。
  path              : string;
begin
  path := ExtractFilePath(Application.ExeName); //程序路徑
  if path[Length(path)] <> '/' then
    path := path + '/';
  ADOConnection.Connected := False;
  try
    ADOConnection.ConnectionString :=
      'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' +
      path + 'Data.MDB' + ';Persist Security Info=False';
    ADOConnection.Connected := true;
  except
    MessageBox(GetActiveWindow(), '系統錯誤!', '警告', MB_OK + MB_ICONWARNING);
    application.Terminate;
  end;
end;

end.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章