Você está na página 1de 13

Exemplo de uso do FreePascal, Lazarus e Firebird

Data da ltima atualizao: 11/06/2004 {********************************************************************* * DESENVOLVIDO POR: Eduardo Jedliczka. Publicado em www.firebase.com.br com autorizao do autor. Programa Exemplo de Tecnologia Open-Source e FreeWare. Desenvolvido em FreePascal 1.9.2 (Aka 2.0.0 beta 2 ) - Maro de 2004. e FreePascal 1.9.3 (Aka 2.0.0 beta 3 - Pr) que acompanha o Lazarus 0.9.1.4 de 19 de Abril de 2004. FireBird 1.0.3 Build 972. Testado nas Plataformas Linux (Slackware 8.1) e Windows (9x e XP). **********************************************************************
y y y y

y y y

y y

Nesta Verso do FreePascal, o componente TIBQuery possui as seguintes caractersticas: case-sensitive, ou seja, faz distino de campos definidos em letras minsculas e maisculas! No faz validao se a Query est aberta em um Query.Close causando assim "Algumas" Violaes de Acesso. Curiosamente, aps liberar a query (Query.Free) no possvel recriar o componente (Invalid Pointer Operation) Isto tambm acontece com outros objetos nesta verso do Compilador. Comumente a query no fechada aps um Query.Close, o que pode acarretar o problema abaixo. Aps um Sql.Clear, Vez ou outra se faz necessrio Reiniciar a Transao. O TStringList (Tipo da Propriedade Sql) no se mantm estvel diante de sucessivas concatenaes de Strings (Principalmente quando se usa strings concatenadas com funes que retornam strings). O Mtodo First, no funciona! Aparentemente est setando o flag "EOF" (fim de arquivo). Os mtodos Append, Insert, Edit e Post, esto definidos, mas seus cdigos ainda no foram devidamente implementados.

Provavelmente esteja disponvel na verso 2.0 Final. (Disponibilizando compatibilidade "quase plena" com a paleta IBX do Delphi. Historicamente o FreePascal sempre tem uma "verso" em Julho, o que animador, mas provavelmente a verso final no sair este ano. ********************************************************************** }

program AgendaFireBird; {$MODE DELPHI} {$ifdef unix} {$ifndef BSD} // BSD possui a libdl dentro da libc {$linklib dl} {$endif} {$linklib crypt} {$endif} uses Interbase, SysUtils, Crt; var Database : TIBDatabase; Trans : TIBTransaction; Query : TIBQuery; OP, Codigo : Integer; Nome, Telefone : String;

// Cadastra uma Pessoa na Agenda... procedure Cadastra; begin // Monta uma tela bem simples... ClrScr; WriteLn('*********************'); WriteLn('Agenda 1.0 - Cadastro'); WriteLn('*********************'); WriteLn; WriteLn('Deixe o nome em branco para sair...'); WriteLn; Nome := ''; Telefone := ''; //Solicita o Nome Write('Informe o Nome: '); ReadLn(Nome); if Nome='' then Exit; //Solicita o telefone... Write('Informe o Fone: '); ReadLn(Telefone); WriteLn; try Query.Close; Query.SQL.Clear; WriteLn('Inserindo Registro'); // Inicia a transao... o mtodo Trans.StartTransaction no est estvel... Trans.Action := caCommitRetaining; Trans.Active := True; // Apesar da query j possuir o mtodo prepare, os parmetros no so //informados corretamente, sendo assim optei em utilizar tudo em uma //nica linha. Query.SQL.Add( 'Insert into Agenda (Nome, Telefone) Values ('''+ Nome + ''', ''' + Telefone + ''')' ); // Executa a query... Query.ExecSQL; // Comita a Transao Trans.Commit; WriteLn('Registro Inserido...'); except // Se falhar... on E:Exception do begin WriteLn('Erro Inserindo Registro...'); Query.SQL.Clear; // Realiza um rollback... Trans.Rollback; end; end; WriteLn; end;

// Altera os dados de uma pessoa na Agenda. procedure Altera; var S : String; NomeNovo : String; FoneNovo : String; begin // Monta uma tela bem simples... ClrScr; WriteLn('**********************'); WriteLn('Agenda 1.0 - Alterao'); WriteLn('**********************'); WriteLn; WriteLn('Informe 0 (Zero) para sair...'); WriteLn; Codigo := 0; // Solicita o cdigo a alterar... Write('Cdigo a Alterar: '); ReadLn( Codigo ); if Codigo = 0 then Exit; // Inicia a transao... o mtodo Trans.StartTransaction no est estvel... Trans.Action := caCommitRetaining; Trans.Active := True; WriteLn('Buscando Registro...'); Query.SQL.Clear; Query.SQL.Add( 'Select First 1 * From Agenda Where Codigo=' + IntToStr(Codigo) ); // Abre a query, e recupera os dados... Query.Open; Codigo := Query.FieldByName('CODIGO') .AsInteger; Nome := Query.FieldByName('NOME') .AsString; Telefone := Query.FieldByName('TELEFONE') .AsString; // Fecha a query e a transao... Query.Close; Trans.Commit; Query.SQL.Clear; // Se o cdigo informado no estiver disponvel no banco de dados, sai da rotina. if Codigo = 0 then begin WriteLn('Registro no encontrado...'); exit; end; WriteLn; WriteLn('Dados Atuais'); WriteLn('Nome....: ', Nome); WriteLn('Telefone: ', Telefone); WriteLn; WriteLn; WriteLn('Informe os Novos Dados (Deixe em branco para manter)'); Write('Nome....: '); ReadLn(NomeNovo); Write('Telefone: '); ReadLn(FoneNovo); WriteLn; // S grava se foi alterado o nome ou telefone! if NomeNovo = Nome then NomeNovo := ''; if FoneNovo = Telefone then FoneNovo := ''; if (NomeNovo = '') and (FoneNovo = '') then begin

WriteLn('No a dados a alterar!'); exit; end; try S := ''; if ( NomeNovo <> '' ) then S := 'Nome=''' + NomeNovo + ''''; if ( FoneNovo <> '' ) then begin if ( S <> '' ) then S := S + ', '; S := S + 'Telefone=''' + FoneNovo + ''''; end; // Monta o Update apenas dos dados alterados... S := 'Update Agenda Set ' + S + ' Where Codigo='; S := S + IntToStr(Codigo); //WriteLn ( S ); Query.SQL.Add( S ); // Inicia a transao... o mtodo Trans.StartTransaction no est estvel... Trans.Action := caCommitRetaining; Trans.Active := True; // Executa a Query e commita a transao... Query.ExecSQL; Trans.Commit; Query.SQL.Clear; WriteLn('Registro alterado...'); except // Se falhar, mostra uma mensagem e faz um rollback... on E:Exception do begin Query.SQL.Clear; WriteLn('Erro Alterando Registro...'); Trans.Rollback; end; end; end;

// Apaga uma pessoa da agenda... procedure Exclui; var Ok : String; begin // Monta uma tela bem simples... ClrScr; WriteLn('*********************'); WriteLn('Agenda 1.0 - Excluso'); WriteLn('*********************'); WriteLn; WriteLn('Informe 0 (Zero) para sair...'); WriteLn; // Solicita o cdigo para excluir... Codigo := 0; Write('Cdigo a Excluir: '); ReadLn( Codigo ); if Codigo = 0 then Exit; Query.SQL.Clear; // Inicia a transao... Trans.Action := caCommitRetaining; Trans.Active := True; WriteLn('Buscando Registro...'); Query.SQL.Add( 'Select First 1 * From Agenda Where Codigo=' + IntToStr(Codigo) ); // Abre a query, recupera os campos e fecha a transao... Query.Open; Codigo := Query.FieldByName('CODIGO') .AsInteger; Nome := Query.FieldByName('NOME') .AsString; Telefone := Query.FieldByName('TELEFONE') .AsString; Query.Close; Trans.Commit; Query.SQL.Clear; if Codigo = 0 then begin WriteLn('Registro no encontrado...'); exit; end; // Exibe os dados atuais... WriteLn; WriteLn('Dados Atuais'); WriteLn('Nome....: ', Nome); WriteLn('Telefone: ', Telefone); WriteLn; WriteLn; Write('Deseja Realmente Excluir este registro ? [S]im ou [N]o: '); ReadLn( Ok ); if Ok <> 'S' then begin exit; end; try // Inicia a transao... Trans.Action := caCommitRetaining; Trans.Active := True; // Monta a query e exclui o registro... Query.SQL.Add( 'Delete from Agenda Where Codigo=' + IntToStr(Codigo) ); Query.ExecSQL; //Commita a transao... Trans.Commit;

Query.SQL.Clear; WriteLn('Registro Excludo...'); except // Se falhar, faz um rollback... on E:Exception do begin Query.SQL.Clear; WriteLn('Erro excluindo Registro...'); Trans.Rollback; end; end; end;

// Lista todos os registros na tela em ordem alfabtica... procedure ListaTodos; Var Linha : Integer; begin // Monta uma tela bem simples... ClrScr; WriteLn('************************'); WriteLn('Agenda 1.0 - Lista Todos'); WriteLn('************************'); WriteLn; Linha := 6; GotoXy( 1,5); Write('Codigo'); GotoXy( 8,5); Write('Nome'); GotoXy(70,5); Write('Telefone'); // Inicia a transao... Trans.Action := caCommitRetaining; Trans.Active := True; // Monta a Query... Query.SQL.Text := 'Select * From Agenda Order By Nome'; try Query.Open; // Enquanto tiver registros... While Not Query.Eof do begin // Faz o salto de pgina, mas espera uma tecla... if Linha > 23 then begin Repeat Until KeyPressed; ClrScr; Linha := 2; GotoXy( 1,1); Write('Nome'); GotoXy(62,1); Write('Telefone'); end; // Imprime a linha... GotoXy( 1, Linha ); Write( Query.FieldByName('CODIGO') .AsInteger:6); GotoXy( 8, Linha ); Write( Query.FieldByName('NOME') .AsString); GotoXy(63, Linha ); Write( Query.FieldByName('TELEFONE').AsString:15); Inc(Linha); // Avana um registro... Query.Next; end; // Termina a Transao... Query.Close; Trans.Commit; Query.Sql.Text := ''; except // Se falhar, faz um rollback... on E:Exception do begin Query.Close; WriteLn; WriteLn('Erro Consultando Registros...'); Trans.Rollback; Query.Sql.Text := ''; end; end; WriteLn; end;

// Rotina principal do programa... var Ok : Boolean; begin // Inicializa a conexo com o banco e a transao... WriteLn; WriteLn('Criando componentes...'); Database := TIBDatabase.Create(nil); Trans := TIBTransaction.Create(nil); // Database.DatabaseName := '192.168.238.1://testes/agenda.fdb'; DataBase.Dialect := 3; Database.UserName := 'SYSDBA'; Database.Password := 'masterkey'; Database.Transaction := Trans; DataBase.CharSet := 'WIN1252'; Database.DatabaseName := 'C:\rede\Testes-Linux\estagio\Agenda.fdb'; // Tenta conectar com o banco, se falhar finaliza o aplicativo... Write('Abrindo Banco... Conectou ? '); try Database.Open; Ok := Database.Connected except Ok := False; end; if not Ok then begin WriteLn('No!'); WriteLn('Abandonando o sistema!'); end else begin WriteLn('Sim!'); //Cria a query... Query := TIBQuery.Create(nil); // Liga a Query ao Banco de Dados e a transao... Query.Database := Database; Query.Transaction := Trans; Op := 1; // Menu principal do programa... while Op <> 0 do begin ClrScr; WriteLn('******************************************************'); WriteLn('Controle de Agenda 1.0 - Modo Console ( 32 bits Real )'); WriteLn('******************************************************'); WriteLn; WriteLn; WriteLn('1 - Cadastrar'); WriteLn('2 - Alterar'); WriteLn('3 - Excluir'); WriteLn('4 - Listar Todos'); WriteLn('0 - Sair'); WriteLn; WriteLn; WriteLn('Aviso! Todas as opes deste programa esto funcionando!'); WriteLn; WriteLn('Mas, o compilador ainda no 100% confivel, portando, ' + 'determinadas opes,'); WriteLn('quando executadas mais de uma vez sem reiniciar o programa, '

+ 'podem falhar.'); WriteLn; // Le o menu e executa as opes... Write('Informe a opo desejada: '); ReadLn( Op ); case op of 1: Cadastra; 2: Altera; 3: Exclui; 4: ListaTodos; end; if Op <> 0 then begin WriteLn; WriteLn('Pressione qualquer tecla para continuar...'); Repeat Until KeyPressed; end; end; WriteLn('Fechando Query...'); Trans.Commit; Query.Free; end; Write('Desconectando banco de dados...'); Database.Close; WriteLn; Trans.Free; DataBase.Free; { WriteLn('Pressione qualquer tecla para continuar...'); Repeat Until KeyPressed; } end.

/********************************************************************* ********/ /**** Generated by IBExpert 2004.04.01 24/05/2004 12:44:56 ****/ /********************************************************************* ********/ SET SQL DIALECT 3; SET NAMES WIN1252; CREATE DATABASE 'C:\rede\Testes-Linux\estagio\Agenda.fdb' USER 'SYSDBA' PASSWORD 'masterkey' PAGE_SIZE 4096 DEFAULT CHARACTER SET WIN1252; /********************************************************************* ********/ /**** Domains ****/ /********************************************************************* ********/ CREATE DOMAIN FONE AS VARCHAR(12); CREATE DOMAIN ID AS SMALLINT NOT NULL; CREATE DOMAIN NOME AS VARCHAR(60) NOT NULL; /********************************************************************* ********/ /**** Tables ****/ /********************************************************************* ********/ CREATE TABLE AGENDA ( CODIGO ID NOT NULL, NOME NOME NOT NULL, TELEFONE FONE ); INSERT INTO AGENDA (CODIGO, NOME, TELEFONE) VALUES (1, 'EDUARDO JEDLICZKA', '(43) 422-5962'); COMMIT WORK; /********************************************************************* ********/ /**** Triggers ****/ /********************************************************************* ********/ SET TERM ^ ; /* Trigger: AGENDA_INSERT */ CREATE TRIGGER AGENDA_INSERT FOR AGENDA ACTIVE BEFORE INSERT POSITION 0 AS DECLARE VARIABLE COD INTEGER; begin if ((NEW.CODIGO IS NULL) or (NEW.CODIGO=0)) then begin SELECT MAX(CODIGO) FROM AGENDA INTO :COD; if (COD IS NULL) then COD=0; New.Codigo = Cod + 1; end end

^ SET TERM ; }

Você também pode gostar