Setting "Server" programmatically with a TFDConnection

user2021539 picture user2021539 · Jun 13, 2015 · Viewed 13.6k times · Source

TFDConnection.Params.Server is not a valid published property in Delphi XE7. How can I set the server location programmatically? I have 2 MySQL servers (test and production) that are at different ip's and based on what I am doing in the application, I want to easily switch back and forth between the 2 servers.

Answer

Remy Lebeau picture Remy Lebeau · Jun 13, 2015

Please read the documentation, it tells you exactly how to define a FireDAC connection for MySQL:

Working with Connections (FireDAC)

Connect to MySQL Server (FireDAC)

You would specify the DB server as part of a Connection Definition:

Defining Connection (FireDAC)

Connection Definitions can be defined in an external .ini file, which you can then reference in the TFDManager.ConnectionDefFileName property, or load dynamically using the TFDManager.LoadConnectionDefFile() method.

[MySQL_Connection_1]
DriverID=MySQL
Server=192.168.1.100
...

[MySQL_Connection_2]
DriverID=MySQL
Server=192.168.1.101
...

Or dynamically using the TFDManager.ConnectionDefs property:

var
  oDef: IFDStanConnectionDef;
begin
  oDef := FDManager.ConnectionDefs.AddConnectionDef;
  oDef.Name := 'MySQL_Connection_1';
  oDef.DriverID := 'MySQL';
  oDef.Server := '192.168.1.100';
  ...
  oDef.Apply;

  oDef := FDManager.ConnectionDefs.AddConnectionDef;
  oDef.Name := 'MySQL_Connection_2';
  oDef.DriverID := 'MySQL';
  oDef.Server := '192.168.1.101';
  ...
  oDef.Apply;

var
  oParams: TStrings;
begin
  oParams := TStringList.Create;
  oParams.Add('Server=192.168.1.100');
  ...
  FDManager.AddConnectionDef('MySQL_Connection_1', 'MySQL', oParams);

  oParams.Clear;
  oParams.Add('Server=192.168.1.101');
  ...
  FDManager.AddConnectionDef('MySQL_Connection_2', 'MySQL', oParams);

Either way, you can then tell TFDConnection which Connection Definition to use to reach each database when needed:

FDConnection1.ConnectionDefName := 'MySQL_Connection_1';
// or: FDConnection1.ConnectionDefName := 'MySQL_Connection_2';
FDConnection1.Connected := True;

Alternatively, you can specify the connection parameters directly in the TFDConnection.Params property if you do not want to pre-define separate connection definitions:

FDConnection1.DriverName := 'MySQL';
FDConnection1.Params.Clear;
FDConnection1.Params.Add('Server=192.168.1.100');
// or: FDConnection1.Params.Values['Server'] := '192.168.1.100';
...
FDConnection1.Connected := True;