Antes lo hacia en un DataModule, al poco tiempo me faltaba pantalla para poner los componentes de base de datos, al final opte por crear los componentes en tiempo real y no me arrepiento de haberlo hecho.
Este proceso lo realizo en cada formulario y nos es más trabajo, sino otra forma de trabajar, para mi, es ideal.
Primero, Definir en TForm:
Código Delphi
[-]...
private
SQLInitDB: TStrings; <-- Aquí introduzco la SQL
SQLWhereText: TStrings; <-- Aquí los parametros de WHERE
adoCnnFrm: TADOConnection;
adoQryFrm: TADOQuery;
dsSrcFrm: TDataSource;
...
...
end;
Segundo, Cuando se crea el TForm:
Código Delphi
[-]...
begin
adoCnnFrm := TADOConnection.Create(Self);
adoCnnFrm.LoginPrompt := False;
adoCnnFrm.ConnectionString := MSSQLServerCfg.ConnectionString; <-- Parámetro que se le pasa para la Conexión
adoQryFrm := TADOQuery.Create(Self);
adoQryFrm.Connection := adoCnnFrm;
dsSrcFrm := TDataSource.Create(Self);
dsSrcFrm.DataSet := adoQryFrm;
dbgGrid.DataSource := dsSrcFrm;
SQLInitDB := TStringList.Create;
SQLInitDB.Add('SELECT');
SQLInitDB.Add(' ...');
SQLInitDB.Add(' ...');
SQLInitDB.Add(' FROM xxyyzz');
SQLWhereText := TStringList.Create;
end;
Tercero, Cuando se busca
Código Delphi
[-]...
var
FieldValue: Integer;
begin
FieldValue := GetIDxxyyzzGrid;
if adoCnnFrm.Connected then
adoCnnFrm.Close;
with adoQryFrm do
begin
SQL.Clear;
SQL.Assign(SQLInitDB);
if (SQLWhereText.Count > 0) then
SQL.Add(SQLWhereText.Text);
Open;
end;
dbgGrid.Update;
with dbgGrid.DataSource.DataSet do
begin
Locate('IDXXYYZZ', FieldValue, [loCaseInsensitive]);
Result := RecordCount;
end;
end;
Cuarto, Cuando se cierre el formulario
Código Delphi
[-]...
begin
SQLInitDB.Free;
SQLWhereText.Free;
adoCnnFrm.Free;
dsSrcFrm.Free;
adoQryFrm.Free;
end;
Y esto me va muy bien.
Un saludo.