Delphi FireDAC在后台线程中从MSSql Server检索记录的方法


本文整理自网络,侵删。

 
 type
    TForm1 = class;

  TFDQueryThread = class(TThread)
  private
    FConnection: TFDConnection;
    FQuery: TFDQuery;
    FForm: TForm1;
  published
    constructor Create(AForm : TForm1);
    destructor Destroy; override;
    procedure Execute; override;
    procedure TransferData;
    property Query : TFDQuery read FQuery;
    property Connection : TFDConnection read FConnection;
    property Form : TForm1 read FForm;
  end;

  TForm1 = class(TForm)
    FDConnection1: TFDConnection;
    FDQuery1: TFDQuery;
    DataSource1: TDataSource;
    DBGrid1: TDBGrid;
    DBNavigator1: TDBNavigator;
    Button1: TButton;
    procedure FormDestroy(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
  public
    QueryThread : TFDQueryThread;
  end;

  var
  Form1: TForm1;

  implementation

  {$R *.dfm}

  { TFDQueryThread }

  constructor TFDQueryThread.Create(AForm : TForm1);
  begin
    inherited Create(True);
    FreeOnTerminate := False;
    FForm := AForm;
    FConnection := TFDConnection.Create(Nil);
    FConnection.Params.Assign(Form.FDConnection1.Params);
    FConnection.LoginPrompt := False;

    FQuery := TFDQuery.Create(Nil);
    FQuery.Connection := Connection;
    FQuery.SQL.Text := Form.FDQuery1.SQL.Text;
  end;

  destructor TFDQueryThread.Destroy;
  begin
    FQuery.Free;
    FConnection.Free;
    inherited;
  end;

  procedure TFDQueryThread.Execute;
  begin
    Query.Open;
    Synchronize(TransferData);
  end;

  procedure TFDQueryThread.TransferData;
  begin
    Form.FDQuery1.DisableControls;
    try
      if Form.FDQuery1.Active then
        Form.FDQuery1.Close;
      Form.FDQuery1.Data := Query.Data;
    finally
      Form.FDQuery1.EnableControls;
    end;
  end;

  procedure TForm1.FormDestroy(Sender: TObject);
  begin
    QueryThread.Free;
  end;

  procedure TForm1.Button1Click(Sender: TObject);
  begin
    if not QueryThread.Finished then
      QueryThread.Start
    else
      ShowMessage('Thread already executed!');
  end;

  procedure TForm1.FormCreate(Sender: TObject);
  begin
    FDQuery1.Open;
    QueryThread := TFDQueryThread.Create(Self);
  end;

  end.

相关阅读 >>

Delphi firemonkey 学习笔记 �c tpopup 控件的使用

Delphi fmx 把内容复制到粘贴板上支持跨平台

Delphi android程序启动过程

Delphi 如何将整数值转换为罗马数字表示形式

Delphi 根据特殊符号字符获取字符串前或后的字符

Delphi xe7使用本身的md5单元进行字符串加密

Delphi 中tresourcestream流使用

Delphi 输出用空格对齐字符串的函数

Delphi获取网卡mac地址的两种方法

Delphi中sendmessage详细资料

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...