GARANTIR DESCONTO

Fórum Arquivo INI erro com Firedac #550311

04/04/2016

0

Bom dia, estou com um seguinte problema, ao carregar um arquivo INI
esse é a mensagem de erro
Código:
---------------------------
teste
---------------------------
[FireDAC][Phys][ODBC][Microsoft][SQL Server Native Client 10.0]Neither DSN nor SERVER keyword supplied.
---------------------------
OK
---------------------------


Se eu colocar os valores direto no FDConexion
Código:
[Window Title]
teste - RAD Studio 10 Seattle - UPrincipal [Stopped] [Built]

[Content]
Connection established successfully.

[OK]


Porem ao carregar os dados no Arquivo Ini ele apresenta o erro que ja relacionei. Ja tenho no projeto FDPhysMSSQLDriverLink1.

O que falta ser feito?
Tiago Santos

Tiago Santos

Responder

Post mais votado

04/04/2016

Qual a estrutura do seu arquivo ini ?
Como está carregando o mesmo para o sistema ?

Como está enviando os paramento para o firidac ?

Raimundo Pereira

Raimundo Pereira
Responder

Gostei + 1

Mais Posts

04/04/2016

Tiago Santos

Boa tarde esse é o arquivo INI

[Conexao]
Usuario=tiago
Senha=masterti
Database=teste_sql
Servidor=192.168.10.5
Porta=8080
drivername=MSSQL

Codigo principal:
unit UPrincipal;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms,Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,
  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.Phys.MSSQLDef, FireDAC.VCLUI.Wait, FireDAC.Comp.UI,
  FireDAC.Phys.ODBCBase, UConexao,FireDAC.Phys.MSSQL, Vcl.ExtDlgs, Data.DB,
  FireDAC.Comp.Client;

type
  TfrmPrincipal = class(TForm)
    btnGravar: TBitBtn;
    btnConexao: TBitBtn;
    Edit1: TEdit;
    edtUsuario: TEdit;
    edtSenha: TEdit;
    edtPorta: TEdit;
    edtServidor: TEdit;
    edtBancoDados: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    Label6: TLabel;
    FDConnection: TFDConnection;
    OpenTextFileDialog: TOpenTextFileDialog;
    FDGUIxWaitCursor1: TFDGUIxWaitCursor;
    btnProcuraBanco: TBitBtn;
    FDPhysMSSQLDriverLink: TFDPhysMSSQLDriverLink;
    procedure FormCreate(Sender: TObject);
    procedure btnProcuraBancoClick(Sender: TObject);
    procedure btnGravarClick(Sender: TObject);
    procedure btnConexaoClick(Sender: TObject);
    procedure FDConnectionBeforeConnect(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  frmPrincipal: TfrmPrincipal;
  conexaoClass : TConexao;

implementation

{$R *.dfm}



// Carrega as informações do arquivo INI nos campos



procedure TfrmPrincipal.FormCreate(Sender: TObject);
begin
     conexaoClass := TConexao.Create(ExtractFilePath(Application.ExeName) + 'Config.ini', 'Conexao');
     conexaoClass.LeINI;

     edtBancoDados.Text := conexaoClass.Database;
     edtServidor.Text   := conexaoClass.Servidor;
     edtPorta.Text      := IntToStr(conexaoClass.Porta);
     edtUsuario.Text    := conexaoClass.Usuario;
     edtSenha.Text      := conexaoClass.Senha;
end;

// Abre o Dialog para informar o caminho e nome do arquivo .FDB


procedure TfrmPrincipal.btnProcuraBancoClick(Sender: TObject);
begin
    if OpenTextFileDialog.Execute then
    begin
        edtBancoDados.Text := OpenTextFileDialog.FileName;
    end;
end;

// Grava no arquivo INI as informações dos Edits


procedure TfrmPrincipal.btnGravarClick(Sender: TObject);
begin
    conexaoClass.GravaINI(edtUsuario.Text, edtSenha.Text, edtServidor.Text, edtBancoDados.Text, StrToInt(edtPorta.Text));
    MessageDlg('Gravado com sucesso!', mtConfirmation, [mbOK], 0);
end;

// Chama o método conectar da classe para carregar os parâmetros do INI
procedure TfrmPrincipal.FDConnectionBeforeConnect(Sender: TObject);
begin
    conexaoClass.Conectar(FDConnection);
end;

// Conecta ou Desconecta do banco conforme o status
procedure TfrmPrincipal.btnConexaoClick(Sender: TObject);
begin
    if not FDConnection.Connected then
    begin
        FDConnection.Connected := True;
        btnConexao.Font.Color := clRed;
        btnConexao.Caption    := 'Desconectar';
    end
    else
    begin
        FDConnection.Connected := false;
        btnConexao.Font.Color := clGreen;
        btnConexao.Caption    := 'Conectar';
    end;


end;
END.


e na outra Unit
unit UConexao;

interface

uses
    IniFiles, SysUtils, Forms, FireDAC.Comp.Client, Dialogs;

type
   TConexao = class
   private
      FPath: string;
      FServidor: string;
      FPorta: integer;
      FDatabase: string;
      FSenha: string;
      FUsuario: string;
      FDriver: string;
      FSecao: string;

   public
      property Path : string read FPath write FPath;
      property Servidor : string read FServidor write FServidor;
      property Porta : integer read FPorta write FPorta;
      property Database : string read FDatabase write FDatabase;
      property Senha : string read FSenha write FSenha;
      property Usuario : string read FUsuario write FUsuario;
      property Driver : string read FDriver write FDriver;
      property Secao : string read FSecao write FSecao;

      constructor Create(Path: string; Secao: string);

      procedure LeINI(); virtual;
      procedure GravaINI(Usuario, Senha, Servidor, Banco: string; Porta: integer); virtual;
      procedure Conectar(var Conexao: TFDConnection); virtual;
   end;


implementation

// Lê o arquivo INI e carrega os parâmetros no componente TFDConnection
procedure TConexao.Conectar(var Conexao: TFDConnection);
begin
     LeINI();

     try
        //Passa os parâmetros para o objeto Conexão
        Conexao.Connected := false;
        Conexao.LoginPrompt := false;
        Conexao.Params.Clear;
        Conexao.Params.Add('hostname='+ Servidor);
        Conexao.Params.Add('user_name='+ Usuario);
        Conexao.Params.Add('password='+ Senha);
        Conexao.Params.Add('port='+ IntToStr(Porta));
        Conexao.Params.Add('Database='+ Database);
        Conexao.Params.Add('DriverID='+ Driver);
     Except
        on E:Exception do
        ShowMessage('Erro ao carregar parâmetros de conexão!'#13#10 + E.Message);
     end;
end;

// Método construtor recebe o caminho do INI e nome da Seção para Leitura
constructor TConexao.Create(Path: string; Secao: string);
begin
    if FileExists(Path) then
    begin
       Self.Path := Path;
       Self.Secao := Secao;
    end
    else
       raise Exception.Create('Arquivo INI para configuração não encontrado.'#13#10'Aplicação será finalizada.');
end;

// Grava os parâmetros recebidos no arquivo INI
procedure TConexao.GravaINI(Usuario, Senha, Servidor, Banco: string; Porta: integer);
var
    ArqIni : TIniFile;
begin
     ArqIni := TIniFile.Create(Path);
     try
        ArqIni.WriteString(Secao, 'Usuario', Usuario);
        ArqIni.WriteString(Secao, 'Senha', Senha);
        ArqIni.WriteString(Secao, 'Database', Banco);
        ArqIni.WriteString(Secao, 'Servidor', Servidor);
        ArqIni.WriteInteger(Secao, 'Porta', Porta);
     finally
         ArqIni.Free;
     end;
end;

// Lê os parâmetros do arquivo INI e atribui para os atributos
procedure TConexao.LeINI();
var
    ArqIni : TIniFile;
begin
     ArqIni := TIniFile.Create(Path);
     try
        Servidor    := ArqIni.ReadString(Secao, 'Servidor', '');
        Porta       := ArqIni.ReadInteger(Secao, 'Porta', 0);
        Database    := ArqIni.ReadString(Secao, 'Database', '');
        Senha       := ArqIni.ReadString(Secao, 'Senha', '');
        Usuario     := ArqIni.ReadString(Secao, 'Usuario', '');
        Driver      := ArqIni.ReadString(Secao, 'drivername', '');
     finally
         ArqIni.Free;
     end;
end;
end.
Responder

Gostei + 0

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar