terça-feira, 16 de junho de 2009

Criando um campo lookup em tempo de execução

Uses
Forms, Classes, Controls, StdCtrls, Db, DBTables, DBCtrls;
type
TForm1 = class(TForm)
Table1: TTable;
Table2: TTable;
Button1: TButton;
DBLookupComboBox1: TDBLookupComboBox;
DataSource1: TDataSource;
Table2Codigo: TFloatField; // Objeto campo chave código usado pelo lookup
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
Nome : string;
begin
with TStringField.Create(Table2) do
begin
FieldName := 'MeuCampoLookup';
FieldKind:= fkLookup;
DataSet := Table2;
Nome := Dataset.Name + FieldName;
KeyFields:= 'Codigo'; //Campo Chave
LookUpDataset:= Table1;
LookUpKeyFields:= 'Codigo'; //Campo Chave
LookUpResultField:= 'Nome'; //Resultado da campo lookup criado
DbLookupCombobox1.DataField:= FieldName;
DataSource1.DataSet:= Dataset;
Table2.FieldDefs.Add(Nome, ftString, 20, false);
end;
DbLookupCombobox1.DataSource:= Datasource1;
Table1.Active:= True;
Table2.Active:= True;
end;
end.

Criando um arquivo de texto

Procedure AddLog;
var
log: textfile;
begin
try
AssignFile(log, 'c:log.log');
if not FileExists('c:log.log') then Rewrite(log,'c:log.log');
Append(log);
WriteLn(log, 'informações a serem inclusas');
finally
CloseFile(log);
end;
end;

Criando tabelas via sql

{Inclua na seção uses: dbTables

- Coloque um TButton no form;

- Escreve no OnClick do Button como abaixo:}


procedure TForm1.Button1Click(Sender: TObject);
var
Q: TQuery;
begin
Q := TQuery.Create(Application);
try
Q.DatabaseName := 'SF';
with Q.SQL do begin
Add('Create Table Funcionarios');
Add('( Codigo AutoInc,');
Add(' Nome Char(30),');
Add(' Salario Money,');
Add(' Depto SmallInt,');
Add(' Primary Key (Codigo) )');
end;
Q.ExecSQL;
finally
Q.Free;
end;
end;

Criando tabelas em tempo de execução 5

If FileExists('c:contatoscontatos.db')=false then
begin
TableContatos.Close;
TableContatos.DatabaseName:='c:contatos';
TableContatos.TableName:='Contatos';
TableContatos.TableType:=ttParadox;
TableContatos.FieldDefs.Clear;
TableContatos.FieldDefs.Add('Cod',ftAutoInc,0,false);
TableContatos.FieldDefs.Add('Contato',ftString,50,false);
TableContatos.FieldDefs.Add('Telefone',ftString,12,false);
TableContatos.FieldDefs.Add('Curso',ftString,20,false);
TableContatos.FieldDefs.Add('Observacao',ftMemo,100,false);
TableContatos.IndexDefs.Clear;
TableContatos.IndexDefs.Add('iCod','Cod',[ixPrimary,ixUnique]);
TableContatos.IndexDefs.Add('iContato','Contato',[ixUnique]);
TableContatos.CreateTable;
TableContatos.Open;
ShowMessage('As tabelas foram criadas com êxito!');
end
else
begin
TableContatos.Close;
TableContatos.DataBaseName:='C:contatos';
TableContatos.TableName:='contatos.db';
TableContatos.Open;
end;

Criando tabelas em tempo de execução 4

Var
Tabela: TTable;
Indices: TIndexOptions;
begin
Tabela:= TTable.Create;
Indices:= [ixPrimary, IxUnique];
with Tabela do
begin
active:= false;
databasename:= 'c:teste';
tablename:= 'Tabela';
tabletype:= ttDefault;
fielddefs.clear;
fielddefs.add('Codigo', ftInteger, 0, false);
...
indexdefs.clear;
indexdefs.add('Codigo_Chave', 'codigo', Indices);
CreateTable;
end;

Criando tabelas em tempo de execução 3

If FileExists('c:contatoscontatos.db')=false then
begin
TableContatos.Close;
TableContatos.DatabaseName:='c:contatos';
TableContatos.TableName:='Contatos';
TableContatos.TableType:=ttParadox;
TableContatos.FieldDefs.Clear;
TableContatos.FieldDefs.Add('Cod',ftAutoInc,0,false);
TableContatos.FieldDefs.Add('Contato',ftString,50,false);
TableContatos.FieldDefs.Add('Telefone',ftString,12,false);
TableContatos.FieldDefs.Add('Curso',ftString,20,false);
TableContatos.FieldDefs.Add('Observacao',ftMemo,100,false);
TableContatos.IndexDefs.Clear;
TableContatos.IndexDefs.Add('iCod','Cod',[ixPrimary,ixUnique]);
TableContatos.IndexDefs.Add('iContato','Contato',[ixUnique]);
TableContatos.CreateTable;
TableContatos.Open;
ShowMessage('As tabelas foram criadas com êxito!');
end
else
begin
TableContatos.Close;
TableContatos.DataBaseName:='C:contatos';
TableContatos.TableName:='contatos.db';
TableContatos.Open;
end;

Criando tabelas em tempo de execução 2

{Criar um arquivo em tempo de execução é relativamente simples, você tem que criar uma instância do objeto TTable, esse objeto(de uma lida no Help TTable e suas propriedades e metodos) tem um método de criação e um de Criar tabela. Depois disso é só definir as propriedades da nova tabela:}


DatabaseName := 'c:lista';
TableName := 'Produtos.dbf';
TableType := ttDbase; //os campos da tabela:

Add('codigo', ftString,7, false);
Add('Nome', ftString, 45, false);

//e os índices:


Add('prod1', 'codigo', []);
Add('prod2', 'Fornecedor', []); //com todos os dados devidamente setados:


CreateTable;
Procedure TMainForm.Inicializa;
var
Table1 : TTable;
begin
{ Criar componente TTable }
Table1 := TTable.create(Application);
{ Definições de Campos e criação do arquivo }
with Table1 do
begin
DatabaseName := 'c:lista';
TableName := 'Produtos.dbf';
TableType := ttDbase;
with FieldDefs do
begin
Clear;
Add('codigo', ftString,7, false);
Add('Nome', ftString, 45, false);
Add('Fornecedor', ftString, 5,false );
Add('Custo', ftCurrency, 0, false );
Add('Venda', ftCurrency, 0, false );
end;
with IndexDefs do
begin
Clear;
Add('prod1', 'codigo', []);
Add('prod2', 'Fornecedor', []);
end;
CreateTable;
end;
end; {Utilizando o tipo ftCurrency, formato de valores do sistema financeiro, o Delphi cria um campo Dbase com N,20,4}