Mainfrm.PAS
上传用户:psxgmh
上传日期:2013-04-08
资源大小:15112k
文件大小:2k
源码类别:

Delphi/CppBuilder

开发平台:

Delphi

  1. unit Mainfrm;
  2. interface
  3. uses
  4.   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  5.   Dialogs, DB, DBTables, Buttons, Grids, DBGrids;
  6. type
  7.   TfrmMain = class(TForm)
  8.     Database1: TDatabase;
  9.     Query1: TQuery;
  10.     DataSource1: TDataSource;
  11.     Database2: TDatabase;
  12.     Query2: TQuery;
  13.     DataSource2: TDataSource;
  14.     btnQuery: TSpeedButton;
  15.     DBGrid1: TDBGrid;
  16.     DBGrid2: TDBGrid;
  17.     Session2: TSession;
  18.     Session1: TSession;
  19.     procedure btnQueryClick(Sender: TObject);
  20.   private
  21.     { Private declarations }
  22.   public
  23.     { Public declarations }
  24.   end;
  25. //后台查询数据库的线程类
  26. TQueryThread = class(TThread)
  27.   private
  28.     FSession: TSession;
  29.     FDatabase: TDataBase;
  30.     FQuery: TQuery;
  31.     FDatasource: TDatasource;
  32.     FQueryException: Exception;
  33.     procedure ConnectDataSource;
  34.     procedure ShowQryError;
  35.   protected
  36.     procedure Execute; override;
  37.   public
  38.     constructor Create(Session: TSession; DataBase:
  39.       TDatabase; Query: TQuery; DataSource: TDataSource);virtual;
  40.   end;
  41. var
  42.   frmMain: TfrmMain;
  43. implementation
  44. {$R *.dfm}
  45. //TQueryThread的实现
  46. constructor TQueryThread.Create(Session: TSession; DataBase:
  47.   TDatabase; Query: TQuery; Datasource: TDataSource);
  48. begin
  49.   inherited Create(False);    //以立即执行方式创建线程
  50.   //将传进来的数据库的相关对象赋给私有变量
  51.   FSession := Session;
  52.   FDatabase := DataBase;
  53.   FQuery := Query;
  54.   FDataSource := Datasource;
  55.   FreeOnTerminate := True;   //  //当线程执行完,终止线程
  56. end;
  57. procedure TQueryThread.Execute;
  58. begin
  59.   try
  60.     FQuery.Open;
  61.     Synchronize(ConnectDataSource);
  62.   except
  63.     FQueryException := ExceptObject as Exception;
  64.     Synchronize(ShowQryError);
  65.   end;
  66. end;
  67. procedure TQueryThread.ConnectDataSource;
  68. begin
  69.   FDataSource.DataSet := FQuery;  //连接DataSource到数据集Query上
  70. end;
  71. procedure TQueryThread.ShowQryError;
  72. begin
  73.   Application.ShowException(FQueryException);
  74. end;
  75. procedure RunBackgroundQuery(Session: TSession; DataBase:
  76. TDataBase;Query: TQuery; DataSource:TDataSource);
  77. begin
  78.   TQueryThread.Create(Session, Database, Query, DataSource);
  79. end;
  80. //TfrmMain实现
  81. procedure TfrmMain.btnQueryClick(Sender: TObject);
  82. begin
  83.   RunBackgroundQuery(Session1, DataBase1, Query1,Datasource1);
  84.   RunBackgroundQuery(Session2, DataBase2, Query2,Datasource2);
  85. end;
  86. end.