delphifiredac

FireDAC: everytime I run this code it gives me EFDEException "Connection must be active"


Whenever I run this code:

procedure TTESTE.BitbtnGeralClick(Sender: TObject);
begin
  BitbtnGeral.Enabled := False;
  VarBtnGeral := True;
  Button1.Click;
  VarBtnGeral := False;
  BitbtnGeral.Enabled := True;
end;

procedure TTESTE.Button1Click(Sender: TObject);
begin
  if VarBtnGeral then
  begin
    FDQ1.Active := False;
    FDQ1.SQL.Clear;
    FDQ1.SQL.Add('SELECT * FROM BOBINAPESADA');
    FDQ1.Active := True;
  end;
end;

procedure TTESTE.FormCreate(Sender: TObject);
begin
  BitBtnGeral.Click;
end;

I get the error:

exception EFDEException FireDAC Comp Client -505 Connection [] must be active

when running the query in FormCreate or BitbtnGeral. However, if I run the query in isolation, it works correctly.


Solution

  • procedure TTESTE.Button1Click(Sender: TObject);
    begin
      if VarBtnGeral then
      begin
        FDConnection1.Active := True;                     // +
        FDQ1.Connection := FDConnection1.Connection;      // +
        FDQ1.Active := False;
        FDQ1.SQL.Clear;
        FDQ1.SQL.Add('SELECT * FROM BOBINAPESADA');
        FDQ1.Active := True;
      end;
    end;
    

    Very little information...

    The TFDQuery component has a Connection property that should be taken from the TFDConnection component.

    You can set the TFDConnection.Active property to True at Design-time. If this happens, it means that the database connection is configured correctly. All you have to do is assign the TFDQuery.Connection property.

    If the connection does not pick up, then you have an error in the DB connection settings.