FireDAC 示例

下面的程式碼示例顯示了使用 FireDAC 在後臺執行緒中從 MSSql Server 檢索記錄的一種方法。測試德爾福 10 西雅圖

正如所寫:

  • 執行緒使用自己的 TFDConnection 和 TFDQuery 檢索資料,並在呼叫 Sychronize() 時將資料傳輸到表單的 FDQuery。

  • Execute 僅檢索一次資料。可以更改它以反覆執行查詢以響應從 VCL 執行緒釋出的訊息。

碼:

  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.