【问题标题】:Verifying if data exists in my Table using TClientDataSet in Delphi在 Delphi 中使用 TClientDataSet 验证我的表中是否存在数据
【发布时间】:2020-02-15 14:43:49
【问题描述】:

我正在尝试使用 TClientDataSet 验证我的表中是否存在 [特定] 数据。我

有没有办法可以在 TClientDataSet 中做到这一点?

出于某种原因,我在这里避免使用查询。

【问题讨论】:

  • 你的 q 不是很清楚。当你说“如果数据存在”时,你的意思是你想知道表中是否有特定的记录,或者只是它是否包含任何数据,不管它是什么?在在线帮助中查找TClietDataSet.Locate 函数。
  • 或者如果你想知道表中是否存在数据,你可以使用IsEmpty。顺便说一句,很有可能将查询用作客户端数据集的数据源。也就是说,我也觉得那部分不清楚。
  • @MartynA 我编辑了我的问题“具体”。
  • @SertacAkyuz 抱歉,如果不是很清楚,但我正在寻找的是具体数据。我已经从下面的答案中得到了它。谢谢。

标签: delphi tclientdataset


【解决方案1】:

下面展示了如何检查TClientDataSet是否包含任何数据以及如何查找它是否包含具有特定值的字段的记录(或包含多个字段中的值组合的记录)

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;

注意,如果有很多记录,将 IndexFieldNames 设置为 'Name;ID' 是为了加快定位操作。

【讨论】:

    【解决方案2】:

    您还可以使用 FindKey,它比 Locate 更快。 对于要验证的列,您必须有一个活动的索引。 例如:

    CDS1.IndexFieldNames := 'Name;ID';
    if CDS1.FindKey(['one',1]) then DoSomething;
    

    Locate 不需要索引,但 FindKey 索引是必需的,创建它需要时间。因此,有时FindKey执行时的利润会因为索引的创建时间而丢失。

    【讨论】:

      猜你喜欢
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多