unit uDBConnection;
{< this unit central in work with DB,
contains FDConnection, FDTable and all FDQueries
needed in other units
}

interface

uses
  System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
  FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait,
  FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.Client, Data.DB, FireDAC.Comp.DataSet,
  FireDAC.Phys.MySQLDef, FireDAC.Phys.MySQL;

type
  TDataBaseUnit = class(TDataModule)
    FDConnection: TFDConnection;
    FDPhysMySQLDriverLink1: TFDPhysMySQLDriverLink;

  private


    { Private declarations }
  public
    { Public declarations }

    function Connect: boolean;
    
  end;

//var
//  DataBaseUnit: TDataBaseUnit;

implementation

{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}

function TDataBaseUnit.Connect: boolean;

var oParams:TStrings;  ErrorInfo:string;

begin

  //Драйвер << Можно отдельно прописать, если он не в папке с EXE
//  FDPhysMySQLDriverLink1.VendorLib:='C:\MySQLDriver\libmysql.dll';
// либо положить его в c:\windows\SysWow64\

 oParams:=TStringList.Create;


 try

  oParams.Add('DataBase=coffeetest_db');
  oParams.Add('Password=masterkey');
  oParams.Add('User_Name=root');
  oParams.Add('Port=3306');
  oParams.Add('Server=localhost');
  oParams.Add('CharacterSet=utf8');

  FDConnection.Params.Assign(oParams);
  FDConnection.DriverName:='MySQL';



   //Пробуем подключиться

   try

   FDConnection.Connected:=true;

   if FDConnection.Connected then

     begin
     Result:=true;

//     showmessage('Connected');
     end else Result:=false;



   except



   on E: EFDDBEngineException do

    case E.Kind of
    ekUserPwdInvalid:


       // user name or password are incorrect
       raise Exception.Create('DBConnection Error. User name or password are incorrect'+
       #13#10+#13#10+E.ClassName+' поднята ошибка, с сообщением : '+E.Message);



    ekUserPwdExpired:


      raise Exception.Create('DBConnection Error. User password is expired'
    +#13#10+#13#10+E.ClassName+' поднята ошибка, с сообщением : '+E.Message);



    ekServerGone:



      raise Exception.Create('DBConnection Error. DBMS is not accessible due to some reason'
      +#13#10+#13#10+E.ClassName+' поднята ошибка, с сообщением : '+E.Message);




    else                // other issues



      raise Exception.Create('DBConnection Error. UnknownMistake'
      +#13#10+#13#10+E.ClassName+' поднята ошибка, с сообщением : '+E.Message);





    end;

    on E : Exception do

      raise Exception.Create(
      E.ClassName+' поднята ошибка, с сообщением : '+#13#10+#13#10+E.Message
      );





   end;




 finally

  FreeAndNil(oParams);

 end;


end;


end.
