如何采用数据库连接池解决数据连接问题 Delphi / Windows SDK/APIhttp://www.delphi2007.net/DelphiDB/html/delphi_20061216110359275.html
如何采用数据库连接池解决数据连接问题?欢迎大家一起讨论
up
关注!!
unit Unit2;
interface
uses
Contnrs, Classes, ADODB, Windows;
type
TConnnectionPool = class(TThread)
private
FConnStr: String;
FMaxConn: Integer;
FConnList: TThreadList;
FUnUseConn: TADOConnection;
procedure GetUnUseConn;
function GetCurrenCout: Integer;
protected
procedure Execute; override;
public
Constructor Create(ConnStr: String; maxConn: Integer = 20);
destructor Destroy; override;
function GetConnection: TADOConnection;
end;
implementation
{ TConnnectionPool }
constructor TConnnectionPool.Create(ConnStr: String; maxConn: Integer);
begin
FreeOnTerminate := True;
FConnStr := FConnStr;
FConnList := TThreadList.Create;
Inherited Create(False);
end;
destructor TConnnectionPool.Destroy;
var
i,count: Integer;
List: TList;
obj: TObject;
begin
List = FConnList.LockList;
if List.Count > 0 then
begin
for i := 0 to List.Count - 1 do
begin
obj := TObject(List.Items[i]);
Obj.Free;
end;
end;
FConnList.Free;
inherited;
end;
procedure TConnnectionPool.Execute;
var
aConn: TADOConnection;
i,count: Integer;
List: TList;
obj: TADOConnection;
begin
while not Terminated do
begin
Count := GetCurrenCout;
if Count < FMaxConn then
begin
aConn := TADOConnection.Create(nil);
aConn.ConnectionString := FConnStr;
aConn.Connected := True;
FConnList.Add(aConn);
end
else if count > FMaxConn then
begin
List := FConnList.LockList;
for i := 0 to List.Count - 1 do
begin
obj := TADOConnection(List.Items[i]);
if(obj.DataSetCount = 0) then
begin
FConnList.Remove(obj);;
obj.Free;
end;
end;
FConnList.UnlockList;
end;
GetUnUseConn;
sleep(50);
end;
end;
function TConnnectionPool.GetConnection: TADOConnection;
var
obj: TADOConnection;
begin
if Assigned(FUnUseConn) then
begin
Result := FUnUseConn;
Exit;
end;
obj := TADOConnection.Create(nil);
obj.ConnectionString := FConnStr;
obj.Connected := True;
FConnList.Add(obj);
Result := obj;
end;
function TConnnectionPool.GetCurrenCout: Integer;
begin
Result := FConnList.LockList.Count;
FConnList.UnlockList;
end;
procedure TConnnectionPool.GetUnUseConn;
var
count,i: Integer;
obj: TADOConnection;
List: TList;
begin
count := GetCurrenCout;
if count < 1 then
begin
FUnUseConn := nil;
Exit;
end;
List := FConnList.LockList;
for i := 0 to List.Count - 1 do
begin
obj := TADOConnection(List.Items[i]);
if(obj.DataSetCount = 0) then
begin
FUnUseConn := obj;
break;
end;
end;
FConnList.UnlockList;
end;
end.
不知道好不好用。。。
gz
。。。
学习
学习
顺路来讨点分,哈哈
我---山西-newsoft
要分