首页 > 代码库 > UniDAC 断线重连方法

UniDAC 断线重连方法

KBM服务端的 UniConnection 要实现断线重连(连接 MSSQLServer), 需要以下几个步骤:

一、修改单元文件:kbmMWUniDAC.pas 

 

procedure TkbmMWUNIDACConnection.InternalOpenConnection(ConnectionPool:TkbmMWCustomConnectionPool);
begin
  // Create new database connection using template.
  with TkbmMWUNIDACConnectionPool(ConnectionPool).FDBTemplate do
  begin
    //  针对UniDAC需要增加这个语句,否则连接数据库失败
    FDatabase.Server := Server;

    FDatabase.Database := Database;
    FDatabase.Username := UserName;
    FDatabase.Password := Password;
    FDatabase.LoginPrompt := False;
    FDatabase.ProviderName := ProviderName;

    
    FDatabase.Port := Port;

    FDatabase.SpecificOptions.Assign(SpecificOptions);

    // 支持unidac重联
    FDatabase.Options.LocalFailover:=Options.LocalFailover;
    FDatabase.OnConnectionLost:=OnConnectionLost;
    FDatabase.AfterConnect:=AfterConnect;

    with TkbmMWUNIDACConnectionPool(ConnectionPool) do
      if Assigned(FOnSetupDBConnection) then
        FOnSetupDBConnection(self,FDatabase);
  end;
 
  if FDatabase.ProviderName=‘SQL Server‘  then
    CoInitialize(nil);

  FDatabase.Open;
end;

  

 

二. 把 UniConnection  的 Options.LocalFailover:=True ; 

 

三. 在 UniConnection  的 ConnectionLost 事件修改如下:

 

procedure TDM.CON_AConnectionLost(Sender: TObject; Component: TComponent;
  ConnLostCause: TConnLostCause; var RetryMode: TRetryMode);
begin
  //断线重联
  if (Sender as TUniConnection).Tag<1 then
  begin
    RetryMode:=rmReconnectExecute;
    (Sender as TUniConnection).Tag:=(Sender as TUniConnection).Tag+1;
  end
  else
  begin
    RetryMode:=rmRaise;
    (Sender as TUniConnection).Tag:=0;
  end;
end;

  

四、如果在服务端的函数里有调用 UniQuery 或其他数据库组件,在函数的开头加:CoInitialize(nil);  结尾加:CoUninitialize;

 


 

 

UniDAC 断线重连方法