当开发人员开始创建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 Components is TSQLQuery then TSQLQuery(Components).SQLConnection := Conn;end;为了避免数据库连接泄漏,我们实现了DSServer的OnDisconnect事件。当客户端断开连接时这段持续将运行。 if GetConnection <> nil then GetConnection.Close;
可以用此方法实现数据集池以及TDataSetProvider池