Delphi AdoConnection Reconnect

I just decided to solve the "Connection" problem when restarting the MSSQL database server, and the connection was disconnected forever.

The only solution so far to restart the program is not always that simple on the server far (and the problem must first be detected).

** The code seems to be working fine, but can an ADO experienced person get deeper into the code and see any bugs / problems or improvements needed for this code? **

Type
  TComponentHelper = class helper for TComponent
     Procedure Reconnect(var AdoConn:TAdoConnection; ConnStr:String);
  end;

procedure TComponentHelper.Reconnect(var AdoConn: TAdoConnection; ConnStr: String);
begin
  if Assigned(AdoConn) then begin
    FreeAndNil(AdoConn);
    AdoConn := TAdoConnection.Create(Self);
    AdoConn.ConnectionString := ConnStr;
    AdoConn.LoginPrompt := false;
    SetConnAdoComponent(Self,AdoConn);
    AdoConn.Open;
  end;
end;

procedure SetConnAdoComponent(aSrc:TComponent; var AdoConn:TAdoConnection);
var
  Ctrl : TComponent;
  i    : Integer;
begin
  if (aSrc = Nil) then Exit;
  if (aSrc.ComponentCount <= 0) then Exit;
  for i:=0 to aSrc.ComponentCount-1 do begin
    Ctrl := aSrc.Components[i];
    if (Ctrl is TAdoQuery) then TAdoQuery(Ctrl).Connection := AdoConn;
    if (Ctrl is TAdoTable) then TAdoTable(Ctrl).Connection := AdoConn;
    if (Ctrl is TAdoDataset) then TAdoDataset(Ctrl).Connection := AdoConn;
  end;
end

I call Reconnect () from the Exception part in TForm or TDataModule, AdoConn is the name of the TAdoConnection component, and ConnStr is the full connection string.

Except
  On E:EOleException do begin
    ReConnect(AdoConn,ConnStr);
  end;
  On E:Exception do begin
    ReConnect(AdoConn,ConnStr);
  end;
End;
+4
source share
1 answer

, TADOConnection, - TADOConnection.ConnectionObject . .

uses ActiveX, ComObj, ADOInt;

function CreateADOConnectionObject: _Connection;
begin
  OleCheck(CoCreateInstance(CLASS_Connection, nil, CLSCTX_INPROC_SERVER or
    CLSCTX_LOCAL_SERVER, IUnknown, Result));
end;

var
  NewConnectionObject: _Connection;
  ConnectionString: WideString;
begin
  ConnectionString := ADOConnection1.ConnectionString;
  NewConnectionObject := CreateADOConnectionObject;
  NewConnectionObject.ConnectionString := ConnectionString;
  ADOConnection1.Close;
  // set the new connection object
  ADOConnection1.ConnectionObject := NewConnectionObject;
  ADOConnection1.Open;
end;

ADOConnection1.ConnectionObject := NewConnectionObject FConnectionObject , TADOConnection.

EOleException.ErrorCode (, E_FAIL) , , .

( SQL). .

: SQL Server 2014 SQLOLEDB.1. SQL, SQL " ". a Close/Open , .

+2

Source: https://habr.com/ru/post/1664544/


All Articles