unit TEST_U1;
// Thomas Wassermann
// Nur ein kleines Beispiel
//!!! Threadproperties nur im OnThreadTerm verwenden nicht abgesichert
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
DB, ADODB, StdCtrls, Grids, DBGrids;
type
TMyThread=Class(TThread)
private
FAC:TAdoConnection;
FADS:TadoDataset;
FConnectionString :
String;
FSQL:
String;
FErrorString:
String;
FStream: TStringStream;
public
Constructor Create(
Const ConnectionString,
SQL:
String;TermProc:TNotifyEvent);
overload;
Destructor Destroy;
override;
Procedure Execute;
override;
Property Dataset:TAdodataset
read Fads;
Property ErrorString:
String read FErrorString ;
Property ResultStream:TStringStream
read FStream;
End;
TForm3 =
class(TForm)
Button1: TButton;
ADS: TADODataSet;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
ADOConnection1: TADOConnection;
procedure Button1Click(Sender: TObject);
private
procedure OnThreadTerm(Sender: TObject);
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
Form3: TForm3;
implementation
uses ActiveX,ComObj,ADOInt;
{$R *.dfm}
procedure TForm3.OnThreadTerm(Sender: TObject);
var
Stream: TStringStream;
RS:Variant;
begin
if TMyThread(Sender).Dataset.Active
then
begin
RS := CreateOleObject('
ADODB.Recordset');
RS.Open(TStreamAdapter.Create(TMyThread(Sender).ResultStream)
as IUnknown);
Ads.Recordset := IUnknown(RS)
as _Recordset;
end
else Showmessage(TMyThread(Sender).ErrorString);
end;
procedure TForm3.Button1Click(Sender: TObject);
begin
TMyThread.Create('
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TP2003;Data Source=DEVTESTSERV\SQL2005'
,'
Select * from Abfragen'
,OnThreadTerm);
end;
{ TMyThread }
constructor TMyThread.Create(
const ConnectionString,
SQL:
String; TermProc: TNotifyEvent);
begin
inherited Create(false);
FreeOnTerminate := true;
OnTerminate := TermProc;
FConnectionString := ConnectionString;
FSQL :=
SQL;
end;
destructor TMyThread.Destroy;
begin
FAC.Free;
FADS.Free;
Fstream.free;
Couninitialize;
inherited;
end;
procedure TMyThread.Execute;
begin
Coinitialize(
nil);
FAC:=TAdoConnection.Create(Application);
FAC.LoginPrompt := false;
FAC.ConnectionString := FConnectionString;
FADS:=TadoDataset.Create(
nil);
FAds.Connection := FAC;
FADS.CommandText := FSQL;
FStream := TStringStream.Create('
');
try
FAds.Open;
FAds.Recordset.Save(TStreamAdapter.Create(Fstream)
as IUnknown,adPersistXML);
FStream.Position := 0;
except
on E:
Exception do FErrorString := E.
Message;
end;
end;
end.