Loading Data from and Saving Data to Files

From RAD Studio
Jump to: navigation, search

Go Up to Connecting an ADO Dataset to a Data Store


The data retrieved via an ADO dataset component can be saved to a file for later retrieval on the same or a different computer. The data is saved in one of two proprietary formats: ADTG or XML. These two file formats are the only formats supported by ADO. However, both formats are not necessarily supported in all versions of ADO. Consult the ADO documentation for the version you are using to determine what save file formats are supported.

Save the data to a file using the SaveToFile method. SaveToFile takes two parameters, the name of the file to which data is saved, and, optionally, the format (ADTG or XML) in which to save the data. Indicate the format for the saved file by setting the Format parameter to pfADTG or pfXML. If the file specified by the FileName parameter already exists, SaveToFile raises an EOleException.

Retrieve the data from file using the LoadFromFile method. LoadFromFile takes a single parameter, the name of the file to load. If the specified file does not exist, LoadFromFile raises an EOleException exception. On calling the LoadFromFile method, the dataset component is automatically activated.

In the example below, the first procedure saves the dataset retrieved by the TADODataSet component ADODataSet1 to a file. The target file is an ADTG file named SaveFile, saved to a local drive. The second procedure loads this saved file into the TADODataSet component ADODataSet2.

procedure TForm1.SaveBtnClick(Sender: TObject);
begin
  if (FileExists("c:\SaveFile")) then
  begin
    DeleteFile("c:\SaveFile");
    StatusBar1.Panels[0].Text := "Save file deleted!";
  end;
  ADODataSet1.SaveToFile("c:\SaveFile", pfADTG);
end;
procedure TForm1.LoadBtnClick(Sender: TObject);
begin
  if (FileExists("c:\SaveFile")) then
    ADODataSet2.LoadFromFile("c:\SaveFile")
  else
    StatusBar1.Panels[0].Text := "Save file does not exist!";
end;
void __fastcall TForm1::SaveBtnClick(TObject *Sender)
{
  if (FileExists("c:\\SaveFile"))
  {
    DeleteFile("c:\\SaveFile");
    Statusbar1->Panels->Items[0]->Text = "Save file deleted!";
  }
  ADODataSet1->SaveToFile("c:\\SaveFile");
}
void __fastcall TForm1::LoadBtnClick(TObject *Sender)
{
  if (FileExists("c:\\SaveFile"))
    ADODataSet1->LoadFromFile("c:\\SaveFile");
  else
    Statusbar1->Panels->Items[0]->Text = "Save file does not exist!";
}

The datasets that save and load the data need not be on the same form as above, in the same application, or even on the same computer. This allows for the briefcase-style transfer of data from one computer to another.

See Also