//一个多线程的数据库查询的程序
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, DBGrids, Db, DBTables, StdCtrls, ADODB;
type
TForm1 = class(TForm)
ds1: TDataSource;
dbgrd1: TDBGrid;
ds2: TDataSource;
dbgrd2: TDBGrid;
btn1: TButton;
qry1: TADOQuery;
qry2: TADOQuery;
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TQueryThread = class(TThread)
private
//
FSession:TSession;
//
FDatabase:TDatabase;
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
constructor TQueryThread.Create(Query:TADOQuery;DataSource:TDataSource);
begin
inherited Create(true);
//
FSession := Session ;
//
FDatabase := DataBase;
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.ConnectDatasource ;
begin
FDatasource.DataSet := FQuery ;
end;
procedure TQueryThread.ShowQryError;
begin
Application.ShowException(FQueryException);
end;
procedure RunBackgroundQuery(Query:TADOQuery;DataSource:TDataSource);
begin
TQueryThread.Create(Query,DataSource);
end;
{$R *.DFM}
procedure TForm1.btn1Click(Sender: TObject);
begin
RunBackgroundQuery(qry1,ds1);
RunBackgroundQuery(qry2,ds2);
end;
end.