Delphi Starter database tutorials, part 3


Saving to / loading from a disk file

Let's add a procedure to save your Books-data on disk.

  1. In the source editor, under Private declarations, add the following lines:

    private
        { Private declarations}
        BooksXML: string;
        function ProgDir: string;
  2. In the implementation section, add the following function:

    function TformBooks.ProgDir: string;
    begin
       Result := ExtractFileDir(Application.ExeName) + '\';
    end;
  3. Modify procedure TformBooks.FormCreate as follows:

    procedure TformBooks.FormCreate(Sender: TObject);
    begin
       BooksXML := ProgDir + 'Books.xml';
       if not FileExists(BooksXML) then begin
         cdsBooks.FieldDefs.Add('TITLE', ftString, 30, False);
         cdsBooks.FieldDefs.Add('AUTHOR', ftString, 30, False);
         cdsBooks.FieldDefs.Add('ISBN', ftString, 13, False);
         cdsBooks.FieldDefs.Add('ID', ftString, 6, False);
         cdsBooks.CreateDataSet;
       end
       else
         cdsBooks.LoadFromFile(BooksXML);
       cdsBooks.MergeChangeLog;
       cdsBooks.LogChanges := False;
    end;
  4. In the Object Inspector, add an OnDestroy event handler to formBooks.
    In the Code Editor, complete the event handler as follows:

    procedure TformBooks.FormDestroy(Sender: TObject);
    begin
       cdsBooks.SaveToFile(BooksXML, dfXML);
    end;
  5. Run your program (press F9) and add a few books, for example:

    Enter some books
  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