Re: Cannot Connect ADOConnection at Run-Time



I think I now have it working. Using some old code I Googled. It is still a mystery to me. It always connected/unconnected if I had set the property Connected to True in design time. If I set the Connected Property to False I was not able to connect TADOConnection.

I am sure there are more simple ways of doing this; however, this works.

Here is what I did....


procedure ReconnectSingleConnection(var db : TAdoConnection); var i, n : integer; DatasetList : Array of TCustomAdoDataset; ThisDataset : TCustomAdoDataset; NewConnection : TAdoConnection; OldName : string; begin {Test when network connection is lost} with db do begin n := DatasetCount; SetLength(DatasetList, n); for i := n-1 downto 0 do begin ThisDataset := Datasets[i]; DatasetList[i] := ThisDataset; ThisDataset.Connection := nil; end; {endfor}

    {Create a new connection}
    CoInitialize(NIL);  {Will Not work without this...}
    NewConnection := TAdoConnection.Create(db.Owner);
    NewConnection.CommandTimeout := CommandTimeout;
    NewConnection.ConnectionString := ConnectionString;
    NewConnection.ConnectionTimeout := ConnectionTimeout;
    NewConnection.DefaultDatabase := DefaultDatabase;
    NewConnection.LoginPrompt := LoginPrompt;
    NewConnection.AfterConnect := AfterConnect;
    NewConnection.BeforeConnect := BeforeConnect;
    NewConnection.OnWillConnect := OnWillConnect;
    OldName := Name;
  end;  {endwith}
  db.Free;
  NewConnection.Name := OldName;  {Must assume the same name}
  db := NewConnection;
  NewConnection.Connected := True;

  {Reconnect}
  for i := 0 to n-1 do begin
    ThisDataset := DatasetList[i];
    ThisDataset.Connection := NewConnection;
  end;  {endfor}
end; {ReconnectSingleConnection}

function TMainForm.ConnectToCustomDB001(ConnectString: WideString): integer;
begin
  try
    dbCustom001.ConnectionString := ConnectString;
    ReconnectSingleConnection(dbCustom001);
    result := 0;
  except
    result := -1;
    exit;
  end;
end;


Does anyone have any comments?

Thank you all for the help.


.