Search code examples
mysqldelphidbexpress

Unknown MYSQL server host 'ServerName'(11001)


I want to try connection with MySQLdatabase with my Delphi Application. I am using dbXpress component TSQLConnection.

When I tried using the Graphic component and test it if it can connect Database. It got connected with using Object inspector option.

But when I tried using the code I am getting error as Unknown MYSQL server host 'ServerName'(11001).

I am not able to get the right solution from google uncle.

Can anyone tell me whats wrong with my code?

Below is My Code.

      Conn := TSQLConnection.Create(nil);
  try
    conn.DriverName:= 'MySQL';
    conn.Params.Add('HostName=127.0.0.1');
    conn.Params.Add('Database=test1');
    conn.Params.Add('UserName=root');
    conn.Params.Add('Password=test');
    conn.LoginPrompt := false;
    try
    conn.Connected := true;
    ShowMessage('Database connected');
    Except
      on E:exception do
       ShowMessage(E.Message);
    end;
  finally
   if Conn.Connected then
     Conn.Connected :=  false;
   FreeAndNil(Conn);
  end;

Please let me know if any more information needed.

Thanks in advance.


Solution

  • The conn.Params list is already propagated with pre-existing values. Therefore you should not .add() your configuration to it, but rather change the current Params.

    So, instead of using

    conn.Params.Add('HostName=127.0.0.1'); // wrong - should update, not add
    conn.Params.Add('Database=test1'); // wrong - should update, not add
    conn.Params.Add('UserName=root'); // wrong - should update, not add
    conn.Params.Add('Password=test'); // wrong - should update, not add
    

    Use

    conn.Params.Values['HostName'] := '127.0.0.1';
    conn.Params.Values['Database'] := 'test1';
    conn.Params.Values['UserName'] := 'root';
    conn.Params.Values['Password'] := 'test';