unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ADODB, SyncObjs, StdCtrls;
type
TAdoConnThread = class;
TForm1 = class(TForm)
ADOConnection1: TADOConnection;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Edit4: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject;
var Action: TCloseAction);
private
Flock: TCriticalSection;
FAdoThread: TAdoConnThread;
procedure ConnDataBase;
public
{ Public declarations }
end;
TAdoConnThread = Class(TThread)
private
AdoForm: TForm1;
procedure AdoConnDataBase;
public
constructor Create(CreateSuspended: Boolean;
AForm: TForm1);
procedure Execute;
override;
end;
var
Form1: TForm1;
implementation
const
CCONNSTR = ' Provider=SQLOLEDB.1;Password= ''%s'';Persist Security Info=True;'
+ ' User ID=''%s'';Initial Catalog= ''%s'';Data Source=''%s''' ;
{$R *.dfm}
{ TAdoConnThread }
procedure TAdoConnThread.AdoConnDataBase;
begin
AdoForm.ConnDataBase;
end;
constructor TAdoConnThread.Create(CreateSuspended: Boolean;
AForm: TForm1);
begin
inherited Create(CreateSuspended);
FreeOnTerminate := True;
AdoForm := AForm;
Resume;
end;
procedure TAdoConnThread.Execute;
begin
while not Terminateddo
begin
AdoForm.Flock.Enter;
try
Synchronize(AdoConnDataBase);
finally
AdoForm.Flock.Leave;
Sleep(200);
//为了CPU占有率减低
end;
end;
end;
{ TForm1 }
procedure TForm1.ConnDataBase;
var
vConnStr: String;
begin
with ADOConnection1do
try
Connected := False;
vConnStr := Format(CCONNSTR, [Edit4.Text, Edit3.Text, Edit2.Text, Edit1.Text]) ;
ConnectionString := vConnStr;
Connected := True;
except
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Flock := TCriticalSection.Create;
FAdoThread := TAdoConnThread.Create(True, Self);
end;
procedure TForm1.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
FAdoThread.Terminate;
Sleep(100);
Flock.Free;
Sleep(20);
end;
end.
//我以为能为你解决问题了! 现在我加个动态设置连接字符串的也没有发现出现什么问题啊。