给你一个例子。
仿照D4编程技术内幕的
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, ADODB, Grids, DBGrids, StdCtrls, ExtCtrls, DBTables;
type
TForm1 = class(TForm)
Button1: TButton;
DBGrid1: TDBGrid;
Query1: TADOQuery;
Button2: TButton;
Session1: TSession;
DataSource1: TDataSource;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
TQueryThread = class(TThread)
//FSession: TSession;
FQuery: TADOQuery;
FDataSource: TDataSource;
FQueryException: Exception;
procedure ConnectDataSource;
procedure ShowQryError;
protected
procedure Execute;
override;
public
constructor Create(Query: TADOQuery;
DataSource: TDataSource);virtual;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure RunBackgroundQuery(Query: TADOQuery;DataSource: TDataSource);
begin
TQueryThread.Create(Query,DataSource);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
DataSource1.DataSet := Query1;
with Query1 do
begin
Close;
SQL.Clear;
SQL.Add('select * from users order by ID');
Open;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
try
Query1.Close;
Query1.SQL.Clear;
Query1.SQL.Add('select * from users order by ID');
RunBackgroundQuery(Query1, DataSource1);
except
end;
end;
{ TQueryThread }
procedure TQueryThread.ConnectDataSource;
begin
FDataSource.DataSet := FQuery;
end;
constructor TQueryThread.Create( Query: TADOQuery;
DataSource: TDataSource);
begin
inherited Create(True);
FQuery := Query;
FDataSource := DataSource;
FreeOnTerminate := True;
Resume;
end;
procedure TQueryThread.Execute;
begin
try
FQuery.Open;
Synchronize(ConnectDataSource);
except
FQueryException := ExceptObject as Exception;
Synchronize(ShowQryError);
end;
end;
procedure TQueryThread.ShowQryError;
begin
Application.ShowException(FQueryException);
end;
end.