How to detect connection lost if network cable is unplugged?

Forum related to the ZDBC API-Layer

Moderators: gto, cipto_kh, EgonHugeist

aktivo
Fresh Boarder
Fresh Boarder
Posts: 1
Joined: 21.10.2010, 09:43

How to detect connection lost if network cable is unplugged?

Postby aktivo » 21.10.2010, 10:09

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.

Wild_Pointer
Expert Boarder
Expert Boarder
Posts: 162
Joined: 18.03.2008, 13:03
Contact:

Postby Wild_Pointer » 21.10.2010, 16:44

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!

cacofony
Fresh Boarder
Fresh Boarder
Posts: 16
Joined: 06.12.2006, 15:24
Location: Perth - Western Australia
Contact:

Postby cacofony » 22.10.2010, 06:55

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;


Return to “ZDBC (ZEOS Database Connectivity)”

Who is online

Users browsing this forum: No registered users and 1 guest