给你一个完整的例子,看看:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DBTables, StdCtrls, Buttons, ExtCtrls, Grids, DBGrids, Db;
type
TForm1 = class(TForm)
Query1: TQuery;
DBGrid1: TDBGrid;
Panel1: TPanel;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
BitBtn3: TBitBtn;
se1: TSession;
Database1: TDatabase;
DataSource1: TDataSource;
BitBtn4: TBitBtn;
procedure BitBtn1Click(Sender: TObject);
procedure BitBtn4Click(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TQueryThread=class(TThread)
private
FQuery: TQuery;
FDataSource: TDataSource;
procedure ConnectDataSource;
protected
procedure Execute; override;
public
constructor Create(Query: TQuery;
DataSource: TDataSource); virtual;
end;
var
Form1: TForm1;
Q1, { 线程查询对象1 }
Q2: TQueryThread; { 线程查询对象2 }
implementation
{$R *.DFM}
{ TQueryThread }
procedure TQueryThread.ConnectDataSource;
begin
FDataSource.DataSet := FQuery;{ 该方法在查询结束后才调用 }
end;
constructor TQueryThread.Create(Query: TQuery; DataSource: TDataSource);
begin
FQuery := Query;
FDataSource := DataSource;
inherited Create(True);
FreeOnTerminate := False;
end;
procedure TQueryThread.Execute;
begin
try
FQuery.Open; { 打开查询 }
Synchronize(ConnectDataSource);{ 线程同步 }
except
ShowMessage('Query Error'); { 线程异常 }
end;
end;
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
if Q1.Suspended then
begin
Q1.Resume;
(Sender as TBItBtn).Caption:='Suspend'
end
else begin
Q1.Suspend;
(Sender as TBItBtn).Caption:='Resume'
end
end;
procedure TForm1.BitBtn4Click(Sender: TObject);
begin
query1.close;
Q1:=TQueryThread.Create(Query1,DataSource1);
end;
procedure TForm1.BitBtn2Click(Sender: TObject);
begin
Q1.Terminate;
Q1.Destroy;
end;
end.