Identify "lost connection" in try except

Discussion of open issues, suggestions and bugs regarding MyDAC (Data Access Components for MySQL) for Delphi, C++Builder, Lazarus (and FPC)
Post Reply
maciejmt
Posts: 27
Joined: Sun 25 Apr 2010 14:14

Identify "lost connection" in try except

Post by maciejmt » Wed 27 Apr 2011 11:02

Hi, Is possible to identify exception "Lost connection ...." ?

Code: Select all

try
  MyQuery.Open;
except on E: Exception do
begin
  // if Lost connection then MyReconnect()
  //else
  ReportLog;
end;

end;

AndreyZ

Post by AndreyZ » Wed 27 Apr 2011 12:28

Hello,

You can use the following code:

Code: Select all

try 
  MyQuery.Open; 
except
  on E: EMyError do begin
    if E.ErrorCode = CR_SERVER_LOST then
      MyReconnect
    else
      ReportLog;
end;
To use the CR_SERVER_LOST constant, you should add the MyCall unit to the USES clause of your unit.
But the better way is to use the OnConnectionLost event to reconnect when the connection is lost. Here is an example:

Code: Select all

procedure TMainForm.MyConnectionConnectionLost(Sender: TObject;
  Component: TComponent; ConnLostCause: TConnLostCause;
  var RetryMode: TRetryMode);
begin
  RetryMode := rmReconnect;
end;
Note that the OnConnectionLost event is arised when the TMyConnection.Options.LocalFailover property is set to True. Also note that you should add the MemData unit to the USES clause to use the OnConnectionLost event handler. For more information please read the "Working in an Unstable Network" topic of the MyDAC documentation. Also, you can look at the FailOver demo that demonstrates the recommended approach for working with unstable networks. You can find the FailOver demo in the %MyDAC_Install_Directory%\Demos\Miscellaneous\FailOver directory.

Post Reply