2,498
社区成员
发帖
与我相关
我的任务
分享
constructor TTestThread.create(CreateSuspended: Boolean);
begin
inherited create(CreateSuspended);
end;
destructor TTestThread.Destroy;
begin
inherited;
end;
procedure TTestThread.execute;
var
con1: TADOConnection;
ADOCommand1: TADOCommand;
begin
inherited;
CoInitialize(nil);
con1 := TADOConnection.Create(nil);
con1.ConnectionString := 'Provider=SQLOLEDB.1;Password=11;Persist Security Info=True;User ID=sa;Initial Catalog=aa;Data Source=127.0.0.1';
con1.Connected := True;
ADOCommand1 := TADOCommand.Create(nil);
ADOCommand1.Connection := con1;
ADOCommand1.CommandText := 'SELECT * FROM TESTTBL';
ADOCommand1.Execute;
ADOCommand1.Free;
con1.Close;
CoUninitialize;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
thread:TTestThread;
begin
thread := TTestThread.create(True);
thread.FreeOnTerminate := True;
thread.execute;
//执行这个后如果查询过程比较长的话整个界面被卡住了
end;
如果是delphi XE7及以上的版本,可以用System.Threading的TTask.Run来运行线程, 这样写起来简单多了:
uses System.Threading;
.............................................
procedure TForm1.Button1Click(Sender: TObject);
begin
TTask.Run(procedure
var
con1: TADOConnection;
ADOCommand1: TADOCommand;
begin
inherited;
CoInitialize(nil);
con1 := TADOConnection.Create(nil);
con1.ConnectionString := 'Provider=SQLOLEDB.1;Password=11;Persist Security Info=True;User ID=sa;Initial Catalog=aa;Data Source=127.0.0.1';
con1.Connected := True;
ADOCommand1 := TADOCommand.Create(nil);
ADOCommand1.Connection := con1;
ADOCommand1.CommandText := 'SELECT * FROM TESTTBL';
ADOCommand1.Execute;
ADOCommand1.Free;
con1.Close;
CoUninitialize;
end);
end;