Jump to content

How to implement database connection pooling in unigui?


ChenHaibin

Recommended Posts

I think you can use a static class as

 

 

TConnectionPool = class

private

class var FConnectionList: TThreadList;

class procedure CloseAll;

public

class function Get: TConnection;

class procedure Release( cn: TConnection);

end

 

.....

 

function TConnectionPoll.Get;

var

LList: TList;

begin

LList := FConnectionList.LockList;

try

if LList.Count = 0 then

Result := TConnection.Create(....)

else

begin

Result := TConnection(LList[0]);

LList.Delete(0);

end

finally

FConnectionList.UnLockList;

end;

end;

 

 

procedure TConnectionPool.CloseAll;

var

LList: TList;

LIndex: integer;

begin

try

for LIndex := 0 to LList.Count-1 do

TConnection(LLIst.Free);

LList.Clear;

finally

FConnectionList.UnLockList;

end;

end;

 

procedure TConnectionPool.Release(cn: TConnection);

var

LList: TList;

begin

LList := FConnectionList.LockList;

try

if LList.Count< MaxPoolSize then

LList.Add(cn)

else

cn.Free;

finally

FConnectionList.UnLockList;

end;

end;

 

....

 

initialization

TConnectionPool.FConnectionList := TThreadList.Create;

finalization

TConnectionPool.CloseAll;

TConnectionPool.FConnectionList.Free;

End..

 

( code is not real, only as example idea).

 

Use:

 

....

var

LCn: TConnection;

begin

....

LCn := TConnectionPool.Get;

try

<your code>

finally

TConnectionPool.Release(cn);

end;

.....

Link to comment
Share on other sites

Thank you! Very nice idea!

In application, I think the object should be created in ServerModule.....Right?

If someone can make a example, it would be better.

 

 

This class can be defined into a new unit. When you need a connection, use it. It is a static class, so it is shared by all sessions. Only use as example:

 

var

LCn: TConnection;

begin

....

LCn := TConnectionPool.Get;

try

<your code>

finally

TConnectionPool.Release(cn);

end;

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...