2,498
社区成员
发帖
与我相关
我的任务
分享
TDisplayThread = class(TThread)
...
private
IsOleInitialized:Boolean;
SQLText : String;
Connection : TADOConnection;
Command : TADOCommand;//象楼主这样使用存储过程,还可以使用TADOStoredProc
...
protected
procedure Execute;override;
public
constructor Create( CreateSuspended : Boolean
; ConnectionString : String
; SQLString : String);
destructor Destroy;override;
end;
constructor TDisplayThread.Create( CreateSuspended : Boolean
; ConnectionString : String
; SQLString : String);
begin
Inherited Create(True);//不管是否一开始就需要运行,先暂停(基本要素还没实例化成功)
IsOleInitialized := False;//要使用ADO,就需要进行COM初始化
Connection := TADOConnection.Create(Nil);//注意这个Connect的Owner参数传空值
Command := TADOCommand.Create(Nil);
Connection.ConnectionString := ConnectionString;
Command.Connection := Connection;
Command.CommandText := 'select ''Test Connection...''';//这是MSSQL可用的测试,不同数据库换之
try
Command.Execute;
except
//数据库连接失败,这里处理,通常需要抛出异常
end;
SQLText := SQLString;
if Not CreateSuspended then
Resume;//如果创建即需执行,就执行起来吧
end;
destructor TDisplayThread.Destroy;
begin
Command.Free;
Connection.Free;
if IsOleInitialized then
CoUninitialize;//线程还是有可能会被意外结束的,所以这里加一个保险
end;
procedure TDisplayThread.Execute;
begin
CoInitializeEx(nil, COINIT_MULTITHREADED);//COM初始化
IsOleInitialized := true;
try
Command.Text := SQLText;
while Not Terminated do
begin
try
Command.Execute;
except
on E:Exception do
begin
LogException(E);
end;
end;
Sleep(10000);
end;
finally
CoUninitialize;//COM调用结束
end;
end;