下面是我写的一小段,要点是每个线程都有自己独立的AdoConnection:
unit DataWriter;
interface
uses
Classes,ADODB,ComObj,Activex,idGlobal,SysUtils,Messages,windows;
type
DataWriteThread = class(TThread)
private
FADOConnection:TADOConnection;
FADOQuery:TADOQuery;
FContentList:TStringList;
FStartIndex,FEndIndex:Integer;
FIndex:Integer;
FContent:string;
protected
procedure Execute;
override;
procedure GetContent;
procedure PostEndThreadMessage;
public
constructor Create(StartIndex,EndIndex:Integer);
end;
implementation
uses mf;
{ Important: Methods and properties of objects in VCL or CLX can only be used
in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure DataWriteThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
}
{ DataWriteThread }
constructor DataWriteThread.Create(StartIndex,EndIndex:Integer);
begin
FStartIndex := StartIndex;
FEndIndex := EndIndex;
FreeOnTerminate := True;
inherited Create(False);
end;
procedure DataWriteThread.Execute;
var
i:Integer;
begin
CoInitialize(0);
FADOConnection := TADOConnection.Create(nil);
FADOQuery := TADOQuery.Create(nil);
try
FADOConnection.ConnectionString := 'Provider=SQLOLEDB.1;Password=123;Persist Security Info=True;User ID=sa;Initial Catalog=pubs;Data Source=zhanghl';
FADOConnection.Open;
FADOQuery.Connection := FADOConnection;
FIndex := FStartIndex;
FADOQuery.CacheSize := 800;
FADOQuery.LockType := ltBatchOptimistic;
FADOQuery.Close;
FADOQuery.SQL.Text := 'select top 1 tm from lw';
FADOQUery.Open;
for i := FStartIndex to FEndIndexdo
begin
Synchronize(GetContent);
try
FADOQuery.Append;
FADOQuery.FieldByName('tm').AsString := FContent;
FADOQuery.Post;
except
end;
end;
FADOQuery.UpdateBatch(arAll);
finally
CoUninitialize;
FreeAndNil(FADOConnection);
FreeAndNil(FADOQuery);
Synchronize(PostEndThreadMessage);
end;
end;
procedure DataWriteThread.GetContent;
begin
FContent := MainForm.ListBox.Items[FIndex];
MainForm.NowDo(FIndex);
FIndex := FIndex + 1;
end;
procedure DataWriteThread.PostEndThreadMessage;
begin
PostMessage(MainForm.Handle,WM_DataWriterEnd,0,0);
end;
end.