procedure MyBackupData(Connection: TAdoConnection; const TableName, targetFile:S tring); var Query: TADOQuery; i: integer; TblName, FieldList, Sql

, Header: string; Ls: TStringList; function QuoteName(const A:String): String; begin Result := '`' + A +'`'; end;

begin Query := TADOQuery.Create(nil); Query.Connection := Connection; Ls := TStringList.Create; try Query.SQL.Text := 'SELECT * FROM ' + TableName; Query.Open; TblName := QuoteName(TableName); Ls.Add(''); Ls.Add('DELETE FROM ' + TblName + ';'); if Query.RecordCount = 0 then begin Ls.SaveToFile(targetFile); Query.Close; Query.Free; Ls.Free; exit; end;

Header := 'INSERT INTO ' + TblName; FieldList := ''; for i := 0 to Query.Fields.Count - 1 do begin

if i > 0 then FieldList := FieldList + ', '; FieldList := FieldList + QuoteName(Query.Fields[i].FieldName); end; Header := Header + '(' + FieldList + ')'; Header := Header + ' VALUES (';

while not Query.Eof do begin Sql := ''; for i := 0 to Query.Fields.Count - 1 do begin if i > 0 then Sql := Sql + ', '; if Query.Fields[i].IsNull then Sql := Sql + 'NULL' else begin Sql := Sql + AnsiQuotedStr(Query.Fields[i].AsString, ''''); end; end; Sql := Header + Sql + ');'; Ls.Add(Sql); Query.Next; end; Query.Close; Ls.SaveToFile(targetFile); finally Query.Free; Ls.Free; end; end;

Berikut contoh penggunaanya:

procedure TForm3.Button1Click(Sender: TObject); var i: integer; begin ADOConnection1.Open('root','--password--'); MyBackupData(ADOConnection1, 'pegawai','c:\datapeg.sql'); ADOConnection1.Close; end;

Sign up to vote on this title
UsefulNot useful