You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Delphi患者搜索应用问题:清空搜索栏时ADOQuery.Active无法停用

患者搜索应用ADOQuery停用问题解决

开发患者搜索应用时遇到问题:清空TEdit搜索栏内容后,无法正常停用ADOQuery.Active,尝试设置ADOQuery1.Active := false也未解决。以下是原实现代码:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Mask, scControls,
  scDBControls, scGrids, scDBGrids, scGPControls, Data.DB, Data.Win.ADODB;

type
  TForm1 = class(TForm)
    ADOConnection1: TADOConnection;
    DataSource1: TDataSource;
    Edit1: TEdit;
    scDBGrid1: TscDBGrid;
    ADOQuery1: TADOQuery;
    ADOQuery1PATIENTId: TAutoIncField;
    ADOQuery1NAME_PAT: TStringField;
    ADOQuery1PRENOM_PAT: TStringField;
    procedure Edit1Change(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Edit1Change(Sender: TObject);
begin
  if Edit1.Text = '' then
    ADOQuery1.Filtered := false
  else
  begin
    ADOQuery1.Active := true;
    ADOQuery1.Filtered := False;
    ADOQuery1.Filter := 'NAME_PAT' + ' LIKE ' + QuotedStr(Edit1.Text + '%');
    ADOQuery1.Filtered := True;
  end;
end;

end.

问题分析与修复

原代码在清空搜索栏时仅关闭了过滤(Filtered := false),但并未实际停用ADOQuery。要解决这个问题,需在Edit内容为空时直接关闭ADOQuery的Active状态,同时优化非空时的查询逻辑:

修改后的Edit1Change方法:

procedure TForm1.Edit1Change(Sender: TObject);
begin
  if Trim(Edit1.Text) = '' then
  begin
    // 清空内容时直接停用查询
    if ADOQuery1.Active then
      ADOQuery1.Active := false;
  end
  else
  begin
    // 确保查询处于激活状态
    if not ADOQuery1.Active then
      ADOQuery1.Active := true;
    // 设置过滤条件
    ADOQuery1.Filtered := False;
    ADOQuery1.Filter := Format('NAME_PAT LIKE %s', [QuotedStr(Edit1.Text + '%')]);
    ADOQuery1.Filtered := True;
  end;
end;

额外优化建议

  • 使用Trim(Edit1.Text)判断,避免空格导致的误判
  • 用Format拼接过滤字符串,代码更易读
  • 若查询SQL是动态加载的,需确保打开前ADOQuery1.SQL.Text已设置好基础查询语句
  • 可添加异常捕获,处理数据库连接或查询错误:
procedure TForm1.Edit1Change(Sender: TObject);
begin
  try
    if Trim(Edit1.Text) = '' then
    begin
      if ADOQuery1.Active then
        ADOQuery1.Active := false;
    end
    else
    begin
      if not ADOQuery1.Active then
        ADOQuery1.Active := true;
      ADOQuery1.Filtered := False;
      ADOQuery1.Filter := Format('NAME_PAT LIKE %s', [QuotedStr(Edit1.Text + '%')]);
      ADOQuery1.Filtered := True;
    end;
  except
    on E: Exception do
      ShowMessage('查询出错: ' + E.Message);
  end;
end;

内容的提问来源于stack exchange,提问作者PATHOFF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 18:50:24