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.