Search code examples
delphitclientdataset

Verifying if data exists in my Table using TClientDataSet in Delphi


I am trying to verify if [specific] data exists in my table using TClientDataSet. I

Is there a way that I can do this in TClientDataSet?

I am avoiding to use query for some reason here.


Solution

  • The following shows how to check whether a TClientDataSet contains any data and how to find whether it contains a record with a field having a specific value (or a record containg a combination of values in multiple fields)

    procedure TForm1.FormCreate(Sender: TObject);
    var
      i : Integer;
      Field : TField;
      S : String;
    begin
    
      //  Create 2 fields in the CDS
    
      Field := TIntegerField.Create(Self);
      Field.FieldName := 'ID';
      Field.FieldKind := fkData;
      Field.DataSet := CDS1;
    
      Field := TStringField.Create(Self);
      Field.FieldName := 'Name';
      Field.Size := 40;
      Field.FieldKind := fkData;
      Field.DataSet := CDS1;
    
      //  Next, set up the CDS; it will be empty initially
      CDS1.CreateDataSet;
    
      if CDS1.IsEmpty then
        ShowMessage('Is empty - no data')
      else
        ShowMessage('Something went wrong');
    
      CDS1.IndexFieldNames := 'Name;ID';
      CDS1.InsertRecord([1, 'One']);
      CDS1.InsertRecord([2, 'Two']);
      CDS1.InsertRecord([3, 'Three']);
    
      ShowMessage('DataSet now contains ' + IntToStr(CDS1.RecordCount) + ' records');
    
      S := 'Two';
      if CDS1.Locate('Name', S, []) then
        ShowMessage('Found record with Name = ' + S)
      else
        ShowMessage('Failed to find record with Name = ' + S);
    
      //  Following shows how to use Locate on more than one field
      //  Note: to use VarArrayOf, you need Variants in your uses list
      if CDS1.Locate('ID;Name', VarArrayOf([1, 'one']), [loCaseInsensitive])  then
        ShowMessage('Found record by multiple criteria');
    end;
    

    Note that setting the IndexFieldNames to 'Name;ID' is to speed up the Locate operation if there are a lot of records.