Delphi Community database tutorials, part 3
Saving to / loading from a disk file

Let's add some code for saving the database to a file.

  1. In the source editor, under Private declarations, add the following lines:
      { Private declarations}
      XmlFile: string;
      DataChanged: Boolean;
  2. In the implementation section, modify procedure TForm1.FormCreate as follows:
    procedure TForm1.FormCreate(Sender: TObject);
      DataChanged := False;
      XmlFile := 'ufodata.xml';
      if FileExists(XmlFile) then
      else begin
        cdsUfo.FieldDefs.Add('ID',       ftString, 10, False);
        cdsUfo.FieldDefs.Add('DESC',     ftString, 25, False);
        cdsUfo.FieldDefs.Add('LOCATION', ftString, 16, False);
        cdsUfo.FieldDefs.Add('COUNTRY',  ftString, 16, False);
        cdsUfo.FieldDefs.Add('CE',       ftString,  1, False);
        cdsUfo.FieldDefs.Add('SOURCE',   ftString, 25, False);
        cdsUfo.FieldDefs.Add('DURAT',    ftString, 16, False);
        cdsUfo.FieldDefs.Add('WIT',      ftString,  5, False);
        cdsUfo.FieldDefs.Add('SHAPE',    ftString, 10, False);
        cdsUfo.FieldDefs.Add('APPEAR',   ftString, 10, False);
        cdsUfo.FieldDefs.Add('SIZE',     ftString, 10, False);
        cdsUfo.FieldDefs.Add('OCC',      ftString,  3, False);
        cdsUfo.FieldDefs.Add('LINK2',    ftString, 50, False);
        cdsUfo.FieldDefs.Add('NOTES',    ftMemo,   10, False);
        DataChanged := True;
      cdsUfo.LogChanges := False;
  3. Select cdsUfo. In the Object Inspector, tab Events, double click next to AfterDelete.
    In the Code Editor, complete the newly created event handler as follows:
    procedure TForm1.cdsUfoAfterDelete(DataSet: TDataSet);
      DataChanged := True;
  4. In the Object Inspector, create an OnClose event handler for Form1.
    In the Code Editor, complete the event handler as follows:
    procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
      if DataChanged then
        cdsUfo.SaveToFile(XmlFile, dfXML);
  5. Run your program (press F9). Add, modify and delete a few records.
  6. Stop the program.
The next time that you run the program, it loads the data from the XML file. Try it :)

Part 2 Database Tutorials - Part 2    Database Tutorials - Part 4 Part 4


Crash Course Delphi  Database tutorials Delphi Starter  FAQ  Tips  Source Code  Downloads  Links