terça-feira, 7 de outubro de 2008

Sobrecarga de método no Delphi

Atendendo a algumas solicitações, desenvolvi um exemplo de sobrecarga de método em delphi. O modelo busca a estrutura contida em um componente tAdoQuery, tQuery, tIbQuery;


unit usobrecargaMetodo;

interface

uses
SysUtils, Classes, Db, DBTables,
IBDatabase, IBCustomDataSet, IBQuery, IBUpdateSQL, ADODB;

type
sobrecargaMetodo = class

private
{pegando a estrutura de acordo com os datasets}
function PegandoEstruturaTabela(q1: TDataSet): tStringList;

public

{retorna uma strigList contendo a estrutura da tabela corrente (ado)}
function EstruturaTabela(q1: tAdoQuery): tStringList; overload;

{retorna uma strigList contendo a estrutura da tabela corrente (bde)}
function EstruturaTabela(q1: tQuery): tStringList; reintroduce; overload;

{retorna uma strigList contendo a estrutura da tabela corrente (ib)}
function EstruturaTabela(q1: tibQuery): tStringList; reintroduce; overload;
end;


{implementação de código}
implementation


{retorna uma strigList contendo a estrutura da tabela corrente}
function sobrecargaMetodo.EstruturaTabela(q1: tAdoQuery): tStringList;
begin
result:= PegandoEstruturaTabela(q1);
end;


{retorna uma strigList contendo a estrutura da tabela corrente}
function sobrecargaMetodo.EstruturaTabela(q1: tQuery): tStringList;
begin
result:= PegandoEstruturaTabela(q1);
end;


{retorna uma strigList contendo a estrutura da tabela corrente}
function sobrecargaMetodo.EstruturaTabela(q1: tibQuery): tStringList;
begin
result:= PegandoEstruturaTabela(q1);
end;


{pegando a estrutura de acordo com os datasets}
function sobrecargaMetodo.PegandoEstruturaTabela(q1: TDataSet): tStringList;
var
i: integer;
tipo, linha: string;
begin

result:= TStringList.Create;
result.Add('Campo;' + 'Tipo;' + 'Tamanho');
result.Add('');

{faz uma contagem até o último campo}
for i:= 0 to q1.FieldCount -1 do
begin

{Pegando os tipos para informar na string grid e no arquivo de texto quando solicitado}
if q1.fieldByName(q1.fields[i].FieldName).DataType = ftBlob then
tipo:= 'Blob'

else if q1.fieldByName(q1.fields[i].FieldName).DataType = ftMemo then
tipo:= 'Memo'

else if (q1.fieldByName(q1.fields[i].FieldName).DataType = ftDate) or
(q1.fieldByName(q1.fields[i].FieldName).DataType = ftTime) or
(q1.fieldByName(q1.fields[i].FieldName).DataType = ftDateTime) then
tipo:= 'DateTime'

else if q1.fieldByName(q1.fields[i].FieldName).DataType = ftInteger then
tipo:= 'Integer'

else if q1.fieldByName(q1.fields[i].FieldName).DataType = ftFloat then
tipo:= 'Float'

else if q1.fieldByName(q1.fields[i].FieldName).DataType = ftAutoInc then
tipo:= 'AutoInc'

else if q1.fieldByName(q1.fields[i].FieldName).DataType = ftSmallInt then
tipo:= 'SmallInt'

else if q1.fieldByName(q1.fields[i].FieldName).DataType = ftWord then
tipo:= 'Word'

else if q1.fieldByName(q1.fields[i].FieldName).DataType = ftCurrency then
tipo:= 'Currency'

else if q1.fieldByName(q1.fields[i].FieldName).DataType = ftBoolean then
tipo:= 'Boolean'

else if (q1.fieldByName(q1.fields[i].FieldName).DataType = ftBytes) or
(q1.fieldByName(q1.fields[i].FieldName).DataType = ftVarBytes) then
tipo:= 'Bytes'

else
tipo:= 'String';


{estruturando o txt tipo interbase para ser importado pelo excell}
linha:= '';

linha:= q1.Fields[i].FieldName + ';' + tipo + ';';
if q1.Fields[i].size <> 0 then
linha:= linha + '(' + intToStr(q1.Fields[i].size) + ')';

{retornando a linha}
result.Add(linha);

end;
end;

end.



Para utilizar basta chamar a função passando qualquer componente query, ibquery ou adoquery aberto. Ex:

* Crie um form com um tButton e dê o nome de button1
* no evento onclick, faça o que está no trecho procedure TForm1.Button1Click(Sender: TObject);


unit uMain;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IBDatabase, IBCustomDataSet, IBQuery, IBUpdateSQL,
usobrecargaMetodo; {importando nossa unit de sobrecarga}

type
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
slList: tstringList; {objeto que receberá a estrutura da tabela}

public
{ Public declarations }
sobrecarga: sobrecargaMetodo; {instanciando o objeto sobrecarga}

end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
{cria a string list}
slList:= tStringList.create;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
{destroi a string list}
slList.free;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
{componentes da paleta interbase}
q1: tibQuery;
db1: tibDatabase;
ibt1: tibtransaction;
begin

{cria os componentes de acesso ao banco}
ibt1:= TIBTransaction.Create(application);
db1:= TIBDatabase.Create(application);
q1:= TIBQuery.Create(application);

try
{configura o componente ibdatabase}
with db1 do
begin
Params.Add('user_name=SYSDBA'); {usuário master}
Params.Add('password=masterkey'); {senha do usuário master}
DatabaseName:= 'C:\dados\produtos.fdb'; {endereço do banco}
LoginPrompt:= false;
DefaultTransaction:= ibt1;
Connected:= true;
end;

{liga o componente query ao database}
q1.Database:= db1;

try
{realiza a consulta na tabela para pegar a estrutura
observe que ela não retorna nenhum registro, somente
a estrutura}
with q1 do
begin
close;
sql.clear;
sql.add(' select * from produtos ');
sql.add(' where codproduto is null ');
open;
end;

{pega a estrutura através de nossa função e
joga no componente string list}
slList:= sobrecarga.EstruturaTabela(q1);

{salva o arquivo no disco}
slList.SaveToFile('c:\teste.txt');

{em caso de excessão, informa ao usuário}
except on e: exception do
messageDlg(e.message, mtInformation, [mbOk], 0);
end;

{limpa os componentes da memória}
finally
begin
ibt1.Free;
db1.Free;
q1.Free;
end;
end;
end;

end.



Este é um exemplo simples de como podemos criar sobrecarga no delphi

Nenhum comentário: