Reputation: 324
I have a function to control server connection. If ado cannot connect in 5 seconds, it should give an error. But connectiontimeout property cannot work.
Here is the code I am using :
function AdoConnectionTester(strServerName, strUserName, strPassword,
strDBName: string; boolShowMessage: boolean): Boolean;
var
ADOConn: TADOConnection;
begin
try
Result := True;
ADOConn := TADOConnection.Create(nil);
ADOConn.LoginPrompt :=False;
ADOConn.Close;
ADOConn.ConnectionString := 'Provider=SQLOLEDB.1; Password='+strPassword+';'+
'Persist Security Info=True;User ID='+strUserName+';'+
'Initial Catalog='+strDBName+';'+
'Data Source='+strServerName;
try
ADOConn.ConnectionTimeout := 5;
ADOConn.Open;
except
on E: Exception do
begin
Result := False;
ShowMessage(E.Message);
end;
end;
if Result then
if boolShowMessage = True then
ShowMessage('OK');
finally
ADOConn.Free;
end;
end;
How can i solve this problem ?
Upvotes: 2
Views: 3848
Reputation: 30715
You didn't say what you mean by "does not work", but I assume you mean that the connection does not time out at the end of the period you specify.
Using the code below and a ConnectionString that is guaranteed to fail (by specifying a non-existent server), it seems that a TAdoConnection will not time-out in under about 9 seconds on my LAN. If a timeout period longer than that is specified, it does indeed time out after a longer period, but the actual time is not closely correlated with the specified time-out value. So specifying a time-out value does "work" in the sense of having an effect, but not seemingly if you want a time-out value as low as yours.
I would be surprised if there is anything that can be done via Ado from Delphi to overcome this limitation. The AdoConnection1.ConnectionTimeout is simply passed on to the Ado ConnectionObject attached to it, and that's on the "other side" of the COM interface, so if it doesn't respond how you want, there is, afaik, nothing you can do about it. Something in the machine's TCPIP settings may have an effect, but I'm not disturbing mine to find out ;=)
Update Prompted by another SO q, I retested my code and the minimum time for the AdoConnection to time out on my LAN has gone donwn to 2.8 seconds, without any hardware change or conscious change of software. Maybe the difference has been caused by something in a Win10 update.
procedure TForm1.TestConnectionTimeOut(Timeout : Integer);
var
T1 : Integer;
begin
T1 := GetTickCount;
AdoConnection1.ConnectionTimeout := Timeout;
try
AdoConnection1.Connected := True;
except
ShowMessage(Exception(ExceptObject).Message + #13#10 + IntToStr(GetTickCount - T1));
end;
end;
Upvotes: 0