Page 1 of 1
How to detect connection lost if network cable is unplugged?
Posted: 21.10.2010, 10:09
by aktivo
I'm using ZeosDBO 6.6.6 stable with C++Builder 2007.
I have application connected to PostgreSQL, when i unplug network cable, ZConnection.Connected property is still = true.
If i try ZConnection.PingServer() exception is raised.
Posted: 21.10.2010, 16:44
by Wild_Pointer
Hello aktivo
in short - you cant detect the connection loss without trying. Executing queries after connection is lost used to lead to Access violation exceptions. In version7 this was fixed.
There are 2 ways to ensure connection:
1) pinging server before every query. If ping does not succeed - disconnect and try again. This method uses network traffic and is not that reliable as connection could be lost after pinging.
2) trying to execute query and if exception of connection loss is raised - try reconnect and execute it again. This does not generate excess network traffic.
It's up to you to chose the one approach that suits you best.
Good luck!
Posted: 22.10.2010, 06:55
by cacofony
I used something like the following; that I call before any of my TZQuery open. I cheat in that I have another object wrapping around my TZQuery so I don't need to remember to do it it happens automatically.
procedure CheckConnection;
function ValidateConnection: boolean;
begin
Result := False;
if IsConnected then
begin
try
Result := FZConnection.PingServer;
except
on E: Exception do
begin
end;
end;
end;
end;
begin
if FZConnection.Connected then
begin
if not ValidateConnection then
begin
FZConnection.Reconnect;
end;
end;
end;
I also monitor WM_POWERBROADCAST and restart the connection after a hardware resume.
procedure WMPowerBroadcast(var Msg: TMessage); message WM_POWERBROADCAST;
PBT_APMRESUMEAUTOMATIC, PBT_APMRESUMECRITICAL, PBT_APMRESUMESUSPEND,
PBT_APMRESUMESTANDBY:
begin
Log('Restarting database connection...');
FZConnect.Reconnect;
end;