to: 天真: <br> unit Unit1; <br> <br> interface <br> <br> uses <br> Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, <br> Dialogs, DBTables, Db; <br> <br> const <br> WM_OPENDATASET = WM_USER + 1; <br> WM_EXECUTESQL = WM_USER + 2; <br> <br> type <br> TThreadDataSet = class(TThread) <br> private <br> procedure WMOpenDataSet(Msg: TMsg); <br> procedure WMExecSQL(Msg: TMsg); <br> protected <br> procedure Execute; override; <br> public <br> procedure Open(DataSet: TDataSet); <br> procedure ExecSQL(DataSet: TDataSet); <br> end; <br> <br> TForm1 = class(TForm) <br> procedure FormCreate(Sender: TObject); <br> procedure FormDestroy(Sender: TObject); <br> private <br> { Private declarations } <br> FThread : TThreadDataSet; <br> public <br> { Public declarations } <br> end; <br> <br> var <br> Form1: TForm1; <br> <br> implementation <br> <br> {$R *.DFM} <br> <br> procedure TThreadDataSet.ExecSQL(DataSet: TDataSet); <br> begin <br> PostThreadMessage(ThreadID, WM_EXECUTESQL, Integer(DataSet), 0); <br> end; <br> <br> procedure TThreadDataSet.Execute; <br> var <br> Msg : TMsg; <br> <br> begin <br> FreeOnTerminate := True; <br> PeekMessage(Msg, 0, WM_USER, WM_USER, PM_NOREMOVE); <br> <br> while not Terminated do begin <br> if GetMessage(Msg, 0, 0, 0) then <br> case Msg.Message of <br> WM_OPENDATASET: WMOpenDataSet(Msg); <br> WM_EXECUTESQL: WMExecSQL(Msg); <br> end; <br> end; <br> end; <br> <br> procedure TThreadDataSet.Open(DataSet: TDataSet); <br> begin <br> PostThreadMessage(ThreadID, WM_OPENDATASET, Integer(DataSet), 0); <br> end; <br> <br> procedure TThreadDataSet.WMExecSQL(Msg: TMsg); <br> var <br> Qry : TQuery; <br> <br> begin <br> try <br> Qry := TQuery(Msg.wParam); <br> try <br> Qry.Open; <br> except <br> Qry.ExecSQL; <br> end; <br> except <br> On E: Exception do <br> ShowMessage(E.Message); <br> end; <br> end; <br> <br> procedure TThreadDataSet.WMOpenDataSet(Msg: TMsg); <br> var <br> Ds : TDataSet; <br> <br> begin <br> try <br> Ds := TDataSet(Msg.wParam); <br> Ds.Open; <br> except <br> On E: Exception do <br> ShowMessage(E.Message); <br> end; <br> end; <br> <br> // --------------------------------------- // <br> <br> procedure TForm1.FormCreate(Sender: TObject); <br> begin <br> FThread := TThreadDataSet.Create(False); <br> FThread.Open(Table1); // Opening a dataset (table or query) <br> FThread.ExecSQL(Query1); // Executing a SQL <br> end; <br> <br> procedure TForm1.FormDestroy(Sender: TObject); <br> begin <br> FThread.Terminate; <br> end; <br> <br> end. <br>