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 debug和release区别

Delphi向当前窗口模拟键盘ctrl+v发送"粘贴"

Delphi 读cpu串号的代码

Delphi richedit 加入链接

Delphi 合并文本行的函数

Delphi xe 制作的萤光时钟,可改作屏保

Delphi tmemo 可以显示、编辑多行文本

Delphi try abort、exit except 、finally end 执行情况

Delphi webbrowser控件的documentcomplete和downloadcomplete的区别

Delphi firedac 连接sql server一些要注意的地方

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



打赏

取消

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

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

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

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

评论

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