delphi 多线程 动态创建ADO
delphi 在多线程中动态连接ADO控件 异常:exception class EOleSysError with message '尚未调用CoInitialize'
如果是使用多线程的话那就在 Execute事件的开头加上 CoInitialize(nil); 结尾加上CoUninitialize()
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,ADODB, DB,ActiveX;//ActiveX 必须
type
TForm1 = class(TForm)
Button1: TButton;
ADOConnection1: TADOConnection;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
TMyThread = class(TThread)
protected
procedure Execute; override;
end;
var
Form1: TForm1;
id:integer;
implementation
{$R *.dfm}
procedure TMyThread.Execute;
var
AdoConn1:TADOConnection;
AdoQuery1:TAdoQuery;
begin
FreeOnTerminate:=true;{这可以让线程执行完毕后随即释放}
CoInitialize(nil);// 重要,解决“尚未调用CoInitialize”,需要引入ActiveX单元
try
AdoConn1:=TADOConnection.Create(Form1);//动态创建ADO控件
AdoConn1.ConnectionString:=Form1.ADOConnection1.ConnectionString;
AdoConn1.LoginPrompt:=false;
AdoConn1.Open;
AdoQuery1:=TAdoQuery.Create(Form1);
AdoQuery1.Connection:=AdoConn1;
with AdoQuery1 do
begin
Close;
SQL.Clear;
SQL.Add('select * from pubgszl');
open;
While not eof do
begin
Form1.Memo1.Lines.Add(FieldByName('gsdm').AsString);
next;
end;
end;
Form1.Memo1.Lines.Add('处理成功.');
AdoConn1.Close;
AdoQuery1.Destroy;
AdoConn1.Destroy;//消除
except
AdoConn1.Destroy;
AdoQuery1.Destroy;
Form1.Memo1.Lines.Add('处理失败.');
end;
CoUninitialize();
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
TMyThread.Create(False);
end;
end.