datasnap xe连接池_datasnap 2011 连接池

当开发人员开始创建Delphi的DataSnap应用时很常见的数据库连接定义方式是每个数据模块建立一个连接。这样做将产生大量的数据库连接,并产生很多问题。

DelphiXe,提供了Session管理,更容易实现控制客户端连到服务器的数据库连接。客户端应用程序bu不会知道这些,服务器将完成所有的事情。

当我们创建一个DataSnap服务器时,最好的做法就是定义一个服务器容器(数据模块),其中包含DataSnap服务器组件和注册所有的服务器应用程序所需的类。在这个容器中,我们将定义一个负责处理服务器的数据库连接的方法。

作为一个例子,我已经实现了服务器容器上的一个的getConnection方法。这个方法负责

为连接池分配连接,这将有每一个客户端连接列表寻找,连接池里包含有每个客户端的连接。

private

{ Private declarations }

ListofConnection : TDictionary;

public

function GetConnection : TSQLConnection;

当服务器收到来自新的客户端的连接到数据库的请求时,getConnection将创建一个新的连接并添加到

连接池清单。如果客户已经有了一个连接相关联,getConnection则只返回的一个SqlConnection实例

。连接池使用线程ID来控制每个客户端的唯一连接。如果您使用的DataSnap2010,你必须用GetThreadSession方法来实现这个功能。

function TServerContainer1.GetConnection: TSQLConnection;

var

dbconn : TSQLConnection;

begin

if ListofConnection.ContainsKey(TDSSessionManager.GetThreadSession.Id) then

Result := ListofConnection[TDSSessionManager.GetThreadSession.Id]

else

begin

dbconn := TSQLConnection.Create(nil);

dbconn.Params.Clear;

dbconn.LoadParamsOnConnect := true;

dbconn.ConnectionName := 'DS Employee';

ListofConnection.Add(TDSSessionManager.GetThreadSession.Id, dbconn);

Result := dbconn;

end;

end;

连接定义后,我们需要更新所有数据集使用此连接,这样服务器的所有方法包括create 和运行时的SQL查询都将要调用getConnection方法。

If you are using the VCL Data components (TSQLQuery, TSQLStoredProc, etc…) on your Server DataModules, the onCreate event is a good place to associate the DataSets with the connection, using the following code.

如果您在服务器上DataModules使用VCL的数据组件(TSQLQuery,TSQLStoredProc等...),

在OnCreate事件是一个设置关联数据集的连接的好地方,可以使用下面的代码来设置。

procedure TServerContainer1.SetConnection(Conn: TSqlConnection);

var

i: integer;

begin

if Conn = nil then

Conn := GetConnection;

else

Conn := Sender;

for i := 0 to ComponentCount - 1 do

if Componentsis TSQLQuery then

TSQLQuery(Components).SQLConnection := Conn;

end;

为了避免数据库连接泄漏,我们实现了DSServer的OnDisconnect事件。当客户端断开连接时这段持续将运行。

if GetConnection <> nil then

GetConnection.Close;

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值