1、CoInitialize 没有调用 (CoInitialize was not called);所以,在使用任何dbGo对象前,必须手 调用CoInitialize和CoUninitialize。调用CoInitialize失败会产生"CoInitialize was not called"例外。
2、画布不允许绘画 (Canvas does not allow drawing);所以,必须通过Synchronize过程来通知主线程访问主窗体上的任何控件。
3、不能使用主ADO连接 (Main TADoConnection cannot be used!);所以,线程中不能使用主线程中TADOConnection对象,每个线程必须创建自己的数据库连接。
procedure TForm2.FormCreate(Sender: TObject);
var
strSQL:string ;
begin
strSQL:='SELECT CustNo,Company FROM customer';
ADOQuery1.Close;
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add(strSQL);
ADOQuery1.Open;
ComboBox1.Clear;
ComboBox2.Clear;
ComboBox3.Clear;
//将客户Company和相关CustNo填到ComboBox中
while not ADOQuery1.Eof do
begin
ComboBox1.AddItem(ADOQuery1.Fields[1].asString, TObject(ADOQuery1.Fields[0].AsInteger));
ADOQuery1.Next;
end ;
ComboBox2.Items.Assign(ComboBox1.Items);
ComboBox3.Items.Assign(ComboBox1.Items);
// 默认选中第一个
ComboBox1.ItemIndex := 0;
ComboBox2.ItemIndex := 0;
ComboBox3.ItemIndex := 0;
end ;
end.
{ADO查询多线程单元}
unit
ADOThread;
interface
uses
Classes,StdCtrls,ADODB;
type
TADOThread = class(TThread)
private
{ Private declarations }
FListBox:TListBox;
FLabel:TLabel;
ConnString:WideString;
FSQLString:string;
procedure UpdateCount;
protected
procedure Execute; override;
public
constructor Create(SQL:string;LB:TListBox;Lab:TLabel);
end ;
implementation
uses Main,SysUtils,ActiveX;
{ TADOThread }
constructor TADOThread.Create(SQL: string; LB: TListBox;Lab:TLabel);
begin
ConnString:=Form2.ADOConnection1.ConnectionString;
FListBox:=LB;
FLabel:=Lab;
FSQLString:=SQL;
Inherited Create(False);
end ;
procedure TADOThread.Execute;
var
Qry:TADOQuery;
i:Integer;
begin
{ Place thread code here }
FreeOnTerminate:=True;
CoInitialize(nil);
//必须调用(需Uses ActiveX)
Qry:=TADOQuery.Create(nil);
try
Qry.ConnectionString:=ConnString; //必须有自己的连接
Qry.Close;
Qry.SQL.Clear;
Qry.SQL.Add(FSQLString);
Qry.Open;
FListBox.Clear;
for i := 0 to 100 do //为了执行久点重复历遍数据集101次
begin
while not Qry.Eof And not Terminated do
begin
FListBox.AddItem(Qry.Fields[0].asstring,nil);
//如果不调用Synchronize,会出现Canvas Does NOT Allow Drawing
Synchronize(UpdateCount);
Qry.Next;
end ;
Qry.First;
FListBox.AddItem('*******',nil);
end ;
finally
Qry.Free;
end ;
CoUninitialize;
end ;
procedure TADOThread.UpdateCount;
begin
FLabel.Caption:=IntToStr(FListBox.Items.Count);
end;