Difference between revisions of "Lazarus Database Tutorial/pt"

From Lazarus wiki
Jump to navigationJump to search
Line 115: Line 115:
 
Veja [[Lazarus Database Tutorial/SampleListing|Sample Console Listing]].
 
Veja [[Lazarus Database Tutorial/SampleListing|Sample Console Listing]].
  
===Connecting to MySQL from a Lazarus Application ===
+
===Conectando ao MySQL de uma Applicação Lazarus ===
  
This tutorial shows how to connect Lazarus to the MySQL database, and execute simple queries, using only the basic Lazarus components; it uses no Data Aware components, but illustrates the principles of interfacing with the database.
+
Este tutorial mostra como conectar o Lazarus ao banco de dados MySQL e executar queries simples usando somente os componentes básicos do Lazarus; ele não usa componentes Data Aware, mas ilustra os princípios de interface com banco de dados.
  
Create a new project in Lazarus:
+
Crie um novo projeto no Lazarus:
  Project -> New Project -> Application
+
  Projeto -> Novo Projeto -> Application
A new automatically generated Form will appear.
+
Um novo formulário gerado automaticamente vai aparecer.
  
Enlarge the form to fill about half of the screen, then re-name the form and its caption to 'TryMySQL'.
+
Aumente a área do formulário até preencher aproximadamente a metade da tela e renomeie o formulário e o seu caption para 'TryMySQL'.
  
From the Standard Component tab place three Edit Boxes on the upper left side of the Form, and immediately above each box place a label. Change the names and captions to 'Host' (and HostLLabel,HostEdit), 'UserName' (and UserLabel, UserEdit) and 'Password' (with PasswdLabel and PasswdEdit). Alternatively you could use LabelledEdit components from the Additional tab.
+
Da aba Standard Component ponha três Edit Boxes do lado superior esquerdo do formulário e imediatamente acima de cada Box ponha um Label. Mude os nomes e captions para 'Host' (e HostLLabel, HostEdit), 'UserName' (e UserLabel, UserEdit) e 'Password' (com PasswdLabel e PasswdEdit). Alternativamente você pode usar componentes LabelledEdit da aba Additional.
  
Select the Passwd Edit box and find the PasswordChar property: change this to * or some other character, so that when you type in a password the characters do not appear on your screen but are echoed by a series of *s. Make sure that the Text property of each edit box is blank.
+
Selecione a caixa Passwd Edit e encontre a propriedade PasswordChar : mude-a para "*" ou algum outro caractere de modo que quando você escreva uma senha os caracteres não apareçam na tela mas sejam representados por uma série de caracteres "*". Certifique-se de que a propriedade Text para cada Edit Box esteja em branco.
  
Now place another Edit box and label at the top of the right side of your form. Change the label to 'Enter SQL Command' and name it CommandEdit.
+
Agora ponha outra Edit Box e o Label correspondente no topo direito do formulário. Mude o Label para 'Enter SQL Command' e o seu nome para CommandEdit.
  
Place three Buttons on the formtwo on the left under the Edit boxes, and one on the right under the command box.
+
Coloque três Buttons no formulário: dois do lado esquerdo sob as Edit Boxes e um do lado direito sob a Command Box.
  
Label the buttons on the left 'Connect to Database' (ConnectButton)and 'Exit' (ExitButton) and the one on the right 'Send Query' (QueryButton).
+
Rotule os botões do lado esquerdo como 'Connect to Database' (ConnectButton) e 'Exit' (ExitButton) e o que está do lado direito como 'Send Query' (QueryButton).
  
Place a large Memo Box labelled and named 'Results' (ResultMemo) on the lower right, to fill most of the available space. Find its ScrollBars property and select ssAutoBoth so that scroll bars appear automatically if text fills the space. Make the WordWrap property True.
+
Ponha um Memo grande rotulado e nomeado como 'Results' (ResultMemo) abaixo do lado direito, preenchendo a maior parte do espaço disponível. Encontre a propriedade ScrollBars do Memo e selecione ssAutoBoth , de modo que as Scroll Bars apareçam automaticamente se o texto preencheer o espaço. Configure a propriedade WordWrap como True.
  
Place a Status Bar (from the Common Controls tab) at the bottom of the Form, and make its SimpleText property 'TryMySQL'.
+
Ponha uma Status Bar (da aba Common Controls) embaixo no formulário e faça a propriedade SimpleText igual a 'TryMySQL'.
  
A screenshot of the Form can be seen here: [http://lazarus-ccr.sourceforge.net/kbdata/trymysqldb.png Mysql Example Screenshot]
+
Um screenshot do formulário pode ser visto aqui:
 +
[http://lazarus-ccr.sourceforge.net/kbdata/trymysqldb.png Mysql Example Screenshot]
  
Now we need to write some event handlers.
+
Agora você precisa escrever alguns event handlers.
  
 
The three Edit boxes on the left are for entry of hostname, username and password.  When these have been entered satisfactorily, the Connect Button is clicked.  The OnCLick event handler for this button is based on part of the text-mode FPC program above.
 
The three Edit boxes on the left are for entry of hostname, username and password.  When these have been entered satisfactorily, the Connect Button is clicked.  The OnCLick event handler for this button is based on part of the text-mode FPC program above.

Revision as of 00:07, 11 June 2007

Deutsch (de) English (en) español (es) français (fr) Bahasa Indonesia (id) italiano (it) 日本語 (ja) Nederlands (nl) português (pt) русский (ru) 中文(中国大陆)‎ (zh_CN) 中文(台灣)‎ (zh_TW)

Introdução

Este tutorial mostra como usar o Lazarus com uma variedade de Bancos de dados.

O Lazarus suporta uma diversidade de banco de dados, entretanto os desenvolvedores instalam os pacotes mais adequados para cada um. Você pode acessar o banco de dados por código ou colocando componentes no formulário. Os componentes do tipo data-aware(que precisam de uma fonte de dados para funcionar) representam campos e são conectados ajustando a propriedade DataSource para apontar para o TDataSource. O Datasource representa a tabela e é conectado ao componente do banco de dados (exemplos: TPSQLDatabase, TSQLiteDataSet) ajustando a propriedade DataSet. Os componentes data-aware ficam localizados na aba "Data Controls". O Datasource e o Database estão localizados na aba "Data Access".

Lazarus e MySQL

Comece a trabalhar com MySQL no Linux ou Windows

Siga as instruções no Manual do usuário MySQL. Certifique-se que o mysqld daemon está rodando satisfatoriamente, e que todos os potencias usuários(incluindo root, mysql,você mesmo e qualquer outro que possa necessitá-lo) tenham os privilégios a eles necessários, para os possíveis hosts que possam necessitá-lo(incluindo 'localhost', o hostname local, e outros hosts na sua rede) para manter consistência e segurança. É preferivel que todos os usuários incluindo o root tenham passwords. Teste as ações do sistema de banco de dados usando os exemplos dados no manual do mysql, e certifique-se que todos os usuários sejam confiáveis no acesso.

Comece a trabalhar com FPC no modo texto

Este é o diretório com programa de exemplo $(fpcsrcdir)/packages/base/mysql/. Voce pode encontrar código fonte do FPC (Free Pascal Compiler) no Lazarus: Menu Environment -> Environment Options -> Paths tab -> FPC source directory. Possivelmente o endereço para o mysql seja em /usr/share/fpcsrc/packages/base/mysql (RPM) ou c:\lazarus\fpcsrc\packages\base\mysql\ (no windows). Este diretório contém também as units mysql.pp, mysql_com.pp e mysql_version.pp. Antes de rodar o script de teste, voce necessita criar o banco de dados chamada testdb: faça isso logando-se no prompt do mysql (o root com todos os privilegios) e dando o seguinte comando:

CREATE DATABASE testdb;

Certifique-se que todos os usuário tenham privilegios de acesso apropriados:

GRANT ALL ON testdb TO johnny-user IDENTIFIED BY 'johnnyspassword'; 

Existe um script chamado mkdb que você deve tentar executar:

sh ./mkdb

Este vai provavelmente falhar, já que o sistema não vai autorizar um usuário anônimo a acessar o banco de dados. Então mude o script usando um editor de modo que a linha invocando o MySQL seja:

mysql -u root -p  ${1-testdb} << EOF >/dev/null

e tente executá-lo novamente entrando o seu password no prompt. Com sorte você deve ter conseguido criar o banco de dados de teste: teste-o (enquanto logado no monitor do MySQL) issuing o estamento do MySQL.

select * from FPdev;

Você deve ver uma tabela listando o ID, nome de usuário e e-mail de alguns dos desenvolvedore do FPC.

Agora tente executar o program de teste testdb.pp (ele pode precisar ser compilado e vai quase certamente falhar na primeira tentativa!!).

Eu obtive que o programa não poderia se conectar ao mysql por várias razões:

  • Meu sistema (SuSE Linux v9.0) instal o mysql v4.0.15, não a versão 3 para a qual o pacote foi desenhado.
  • O programa precisa ter nomes de usuários e passwords para ter acesso ao banco de dados.
  • O compilador precisa saber onde encontrar as bibliotecas mysql (se você não instalou as bibliotecas de desenvolvimento MySQL, faça-o agora).

Eu criei uma cópia de testdb.pp chamada trydb.pp em vez de editar o original - isso quer dizer que os arquivos originais ainda são reparados em subseqüentes atualizações do CVS. Também copiei os arquivos do subdiretório mysql/ver40/ para o subdiretório principal mysql/, renomeando-os para mysql_v4.pp, mysql_com_v4.pp and mysql_version_v4.pp, certificando-me de nomear cada unidade dentro de cada arquivo correspondente. Modifiquei o estamento uses em trydb.pp para uses mysql_v4 e o estamento em mysql_v4 para

uses mysql_com_v4

Adicionei uma linha em /etc/fpc.cfg para apontar para minhas bibliotecas:

-Fl/lib;/usr/lib

O passo seguinte pode não ser necessário se as devel-libraries estiverem instaladas como os links que serão criados para você, mas não custa verificar. Eu tive que achar o nome real da biblioteca mysqlclint no diretório /usr/lib e no meu caso tive que entrar o comando:

ln -s libmysqlclient.so.12.0.0 lmysqlclient

para fazer um link simbólico permitindo o FPC achar a biblioteca. Eu também criei o link

ln -s libmysqlclient.so.12.0.0 mysqlclient

e pus links similares em vários outros subdiretórios. Alguns usuários podem precisar adicionar o seguinte link:

ln -s libmysqlclient.so.12.0.0 libmysqlclient.so

Eu modifiquei o trydb.pp para incluir detalhes de usuários, inicialmente adicionando host, usuário e password como constantes:

const
  host : Pchar= 'localhost';
  user : Pchar= 'myusername';
  passwd: Pchar = 'mypassword';

Também achei que não poderia conectar ao mysql usando a chamada mysql_connect(), mas tive que usar mysql_real_connect() que tem muitos mais parâmetros. Para complicar, o número de parâmetros parece ter mudado entre a versão 3 (quando eram sete) e a versão 4 (em que há oito). Antes de usar mysql_real_connect eu tive que usar mysql_init() que não é encontrada no musql.pp original mas o é no mysql_v4.pp.

Assim o código para a conexão ao banco de dados agora é:

{ umas poucas variáveis extra }
var
  alloc : PMYSQL;
 
{fragmento do programa principal }
 
begin
 if paramcount=1 then
   begin
   Dummy:=Paramstr(1)+#0;
   DataBase:=@Dummy[1];
   end;
 
Writeln ('Allocating Space...');
 alloc := mysql_init(PMYSQL(@qmysql));
 Write ('Connecting to MySQL...');
 sock :=  mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
 if sock=Nil then
   begin
   Writeln (stderr,'Couldnt connect to MySQL.');
   Writeln (stderr, 'Error was: ', mysql_error(@qmysql));
   halt(1);
   end;
 Writeln ('Done.');
 Writeln ('Connection data:');
{$ifdef Unix}
 writeln ('Mysql_port      : ',mysql_port);
 writeln ('Mysql_unix_port : ',mysql_unix_port);
{$endif}
 writeln ('Host info       : ',mysql_get_host_info(sock));
 writeln ('Server info     : ',mysql_stat(sock));
 writeln ('Client info     : ',mysql_get_client_info);
 
 Writeln ('Selecting Database ',DataBase,'...');
 if mysql_select_db(sock,DataBase) < 0 then
   begin
   Writeln (stderr,'Couldnt select database ',Database);
   Writeln (stderr,mysql_error(sock));
   halt (1);
   end;
{... as original contents of testdb.pp}

Agora - pronto para começar a compilar trydb.pp?

 fpc trydb

successo! Agora execute:

 ./trydb

Oba! Consegui a lista dos desenvolvedores do FPC!

Uns poucos refinamentos mais: faça a entrada de detalhes dos usuários e os comandos do mysql interativos, usando variáveis em vez de constantes, e permita que vários comandos SQL sejam inseridos, até que o comando quit seja encontrado: veja full program listing, onde os detalhes de usuário são inseridos do console e o programa vai para um loop onde os comandos SQL são inseridos do console (sem ponto e vírgula no final) e as respostas são impressas na tela, até que 'quit' é inserido pelo teclado.

Veja Sample Console Listing.

Conectando ao MySQL de uma Applicação Lazarus

Este tutorial mostra como conectar o Lazarus ao banco de dados MySQL e executar queries simples usando somente os componentes básicos do Lazarus; ele não usa componentes Data Aware, mas ilustra os princípios de interface com banco de dados.

Crie um novo projeto no Lazarus:

Projeto -> Novo Projeto -> Application

Um novo formulário gerado automaticamente vai aparecer.

Aumente a área do formulário até preencher aproximadamente a metade da tela e renomeie o formulário e o seu caption para 'TryMySQL'.

Da aba Standard Component ponha três Edit Boxes do lado superior esquerdo do formulário e imediatamente acima de cada Box ponha um Label. Mude os nomes e captions para 'Host' (e HostLLabel, HostEdit), 'UserName' (e UserLabel, UserEdit) e 'Password' (com PasswdLabel e PasswdEdit). Alternativamente você pode usar componentes LabelledEdit da aba Additional.

Selecione a caixa Passwd Edit e encontre a propriedade PasswordChar : mude-a para "*" ou algum outro caractere de modo que quando você escreva uma senha os caracteres não apareçam na tela mas sejam representados por uma série de caracteres "*". Certifique-se de que a propriedade Text para cada Edit Box esteja em branco.

Agora ponha outra Edit Box e o Label correspondente no topo direito do formulário. Mude o Label para 'Enter SQL Command' e o seu nome para CommandEdit.

Coloque três Buttons no formulário: dois do lado esquerdo sob as Edit Boxes e um do lado direito sob a Command Box.

Rotule os botões do lado esquerdo como 'Connect to Database' (ConnectButton) e 'Exit' (ExitButton) e o que está do lado direito como 'Send Query' (QueryButton).

Ponha um Memo grande rotulado e nomeado como 'Results' (ResultMemo) abaixo do lado direito, preenchendo a maior parte do espaço disponível. Encontre a propriedade ScrollBars do Memo e selecione ssAutoBoth , de modo que as Scroll Bars apareçam automaticamente se o texto preencheer o espaço. Configure a propriedade WordWrap como True.

Ponha uma Status Bar (da aba Common Controls) embaixo no formulário e faça a propriedade SimpleText igual a 'TryMySQL'.

Um screenshot do formulário pode ser visto aqui: Mysql Example Screenshot

Agora você precisa escrever alguns event handlers.

The three Edit boxes on the left are for entry of hostname, username and password. When these have been entered satisfactorily, the Connect Button is clicked. The OnCLick event handler for this button is based on part of the text-mode FPC program above.

The responses from the database cannot now be written using the Pascal write or writeln statements: rather, the replies have to be converted into strings and displayed in the Memo box. Whereas the Pascal write and writeln statements are capable of performing a lot of type conversion 'on the fly', the use of a memo box for text output necessitates the explicit conversion of data types to the correct form of string, so Pchar variables have to be converted to strings using StrPas, and integers have to be converted with IntToStr.

Strings are displayed in the Memo box using

procedure ShowString (S : string);
(* display a string in a Memo box *)
begin
       trymysqlForm1.ResultsMemo.Lines.Add (S)
end;

The ConnectButton event handler thus becomes:

procedure TtrymysqlForm1.ConnectButtonClick(Sender: TObject);
(* Connect to MySQL using user data from Text entry boxes on Main Form *)
var strg: string;
 
begin
 
 dummy1 :=  trymysqlForm1.HostEdit.text+#0;
 host := @dummy1[1];
 dummy2 := trymysqlForm1.UserEdit.text+#0;
 user := @dummy2[1] ;
 dummy3 := trymysqlForm1.PasswdEdit.text+#0;
 passwd := @dummy3[1] ;
 alloc := mysql_init(PMYSQL(@qmysql));
 sock :=  mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
 if sock=Nil then
   begin
     strg :='Couldnt connect to MySQL.'; showstring (strg);
     Strg :='Error was: '+ StrPas(mysql_error(@qmysql)); showstring (strg);
  end
   else
   begin
     trymysqlForm1.statusBar1.simpletext := 'Connected to MySQL';
     strg := 'Now choosing database : ' + database; showstring (strg);
{$ifdef Unix}
     strg :='Mysql_port      : '+ IntToStr(mysql_port); showstring (strg);
     strg :='Mysql_unix_port : ' + StrPas(mysql_unix_port); showstring (strg);
{$endif}
     Strg :='Host info       : ' + StrPas(mysql_get_host_info(sock));
     showstring (strg);
     Strg :='Server info     : ' + StrPas(mysql_stat(sock)); showstring (strg);
     Strg :='Client info     : ' + Strpas(mysql_get_client_info);  showstring (strg);
 
     trymysqlForm1.statusbar1.simpletext := 'Selecting Database ' + DataBase +'...';
 if mysql_select_db(sock,DataBase) < 0 then
 begin
   strg :='Couldnt select database '+ Database; ShowString (strg);
   Strg := mysql_error(sock); ShowString (strg);
 end
 end;
end;


The Text Box on the right allows entry of a SQL statement, without a terminal semicolon; when you are satisfied with its content or syntax, the SendQuery button is pressed, and the query is processed, with results being written in the ResultsMemo box.

The SendQuery event handler is again based on the FPC text-mode version, except that once again explicit type-conversion has to be done before strings are displayed in the box.

A difference from the text-mode FPC program is that if an error condition is detected, the program does not halt and MySQL is not closed; instead, control is returned to the main form and an opportunity is given to correct the entry before the command is re-submitted. The application finally exits (with closure of MySQL) when the Exit Button is clicked.

The code for SendQuery follows:

procedure TtrymysqlForm1.QueryButtonClick(Sender: TObject);
var
 dumquery, strg: string;
begin
     dumquery := TrymysqlForm1.CommandEdit.text;
     dumquery := dumquery+#0;
     query := @dumquery[1];
     trymysqlForm1.statusbar1.simpletext := 'Executing query : '+ dumQuery +'...';
     strg := 'Executing query : ' + dumQuery; showstring (strg);
     if (mysql_query(sock,Query) < 0) then
     begin
       Strg :='Query failed '+ StrPas(mysql_error(sock)); showstring (strg);
     end
     else
     begin
       recbuf := mysql_store_result(sock);
       if RecBuf=Nil then
       begin
         Strg :='Query returned nil result.'; showstring (strg);
       end
       else
       begin
         strg :='Number of records returned  : ' + IntToStr(mysql_num_rows (recbuf));
         Showstring (strg);
         Strg :='Number of fields per record : ' + IntToStr(mysql_num_fields(recbuf));
         showstring (strg);
         rowbuf := mysql_fetch_row(recbuf);
         while (rowbuf <>nil) do
         begin
              Strg :='(Id: '+ rowbuf[0]+', Name: ' + rowbuf[1]+ ', Email : ' +
               rowbuf[2] +')';
              showstring (strg);
              rowbuf := mysql_fetch_row(recbuf);
         end;
       end;
     end;
end;


Save your Project, and press Run -> Run

Download MYSQL Source Code

A full listing of the program is available here Sample Source Code

Lazarus and PostgreSQL

This is a very short tutorial to get Lazarus 0.9.12 or later to connect to a PostgreSQL database, local or remote, using TPQConnection.

After correct install, follow these steps:

  • Place a PQConnection from the SQLdb tab
  • Place a SQLQuery from the SQLdb tab
  • Place a SQLTransaction from the SQLdb tab
  • Place a DataSource from the DataAccess tab
  • Place a DBGrid from the DataControls tab
  • In the PQConnection fill in:
    • transaction property with the respective SQLTransaction object
    • Database name
    • HostName
    • UserName + password
  • Check that the SQLTransaction was automatically changed to point to the PQConnection
  • In the SQLQuery fill in:
    • transaction property with the respective object
    • database property with respective object
    • SQL (something like 'select * from anytable')
  • In the DataSource object fill in the DataSet property with the SQLQuery object
  • In the DBGrid fill in the datasource as the DataSource Object

Turn everything to connected and active and the DBGrid should be filled in design time. TDBText and TDBEdit seem to work but (for me) they only _show_ _data_.

To change contents in the database, I called the DB Engine direct with the following code:

 try
   sql:= 'UPDATE table SET setting=1';
   PQDataBase.Connected:=True;
   PQDataBase.ExecuteDirect('Begin Work;');
   PQDataBase.ExecuteDirect(sql);
   PQDataBase.ExecuteDirect('Commit Work;');
   PQDataBase.Connected:=False;
 except
   on E : EDatabaseError do
     MemoLog.Append('DB ERROR:'+sql+chr(13)+chr(10)+E.ClassName+chr(13)+chr(10)+E.Message);
   on E : Exception do
     MemoLog.Append('ERROR:'+sql+chr(13)+chr(10)+E.ClassName+chr(13)+chr(10)+E.Message);
 end;


  • Notes:
    • Tested on windows, Lazarus 0.9.12 + PgSQL 8.3.1
    • Some tests in linux, Lazarus 0.9.12 and PgSQL 8.0.x


  • Instalation and errors:
    • In the tested version of Lazarus .12, fields of type "text" and "numeric" have bugs
    • I used with no problems char fixed size, int and float8
    • Sometimes restarting Lazarus solves stupid errors...
    • After some errors, the transactions remain active and should be deactivated mannually
    • Changes made in Lazarus are of course not visible until transaction commited
    • The integrated debugger seems buggy (at least in windows) - sometimes running outside of the IDE may help to find errors
    • In linux certain error messages are printed in the console -- run your program in the command line, sometimes there is some extra useful debugging info
    • Error: "Can not load Postgresql client. Is it installed (libpq.so) ?"
      • Add the path to seach libpq* from the PostgreSQL installation.
      • In linux add the path to the libpq.so file to the libraries section in your /etc/fpc.cfg file. For example : -Fl/usr/local/pgsql/lib
      • In windows, add these libs anywhere in the Path environment variable or project dir
      • I windows, I copied all the DLLs in my C:\Program Files\PostgreSQL\8.1\bin dir to another dir in the PATH
      • Or add this postgres\bin dir to the path

Lazarus and SQLite

by Luiz Américo

Introduction

TSqliteDataset and TSqlite3Dataset are TDataset descendants that access, respectively, 2.8.x and 3.2.x sqlite databases. Below is a list of the principal advantages and disadvantages:

Advantages:

  • Flexible: programmers can choose to use or not to use the SQL language, allowing them to work with simple table layouts or any complex layout that SQL/sqlite allows
  • Automatic database update: no need to update the database manually with SQL statements, a single method take cares of it
  • Fast: it caches the data in memory, making browsing in the dataset fast
  • No server instalation/configuration: just ship together with sqlite dynamic library

Disavantages

  • Requires external file (sqlite library)

Requirements

  • For sqlite2 databases:
    • fpc 2.0.0
    • Lazarus 0.9.10
    • sqlite runtime library 2.8.15 or above (get from www.sqlite.org)
  • For sqlite3 databases:
    • fpc 2.0.2
    • Lazarus 0.9.11 (svn revision 8443 or above)
    • sqlite runtime library 3.2.1 or above (get from www.sqlite.org)

Before initiating a lazarus projects, ensure that:

  • the sqlite library is on the system PATH or in the executable directory
  • under Linux, put cmem as the first unit in uses clause of the main program

How To Use (Basic Usage)

Install the package found at /components/sqlite directory (see instructions here)

At design time set the following properties:

  • FileName: path of the sqlite file [required]
  • TableName: name of the table used in the sql statement [required]
  • Sql: a SQL select statement [optional]

Creating a Table (Dataset)

Double click in the component icon or use the 'Create Table' item of the popup menu that appears when clicking the right mouse button. A simple self-explaining table editor will be show.

 Here is all field types supported by TSqliteDataset and TSqlite3Dataset: 
 
 Integer
 AutoInc
 String
 Memo
 Bool 
 Float
 Word
 DateTime
 Date
 Time
 LargeInt
 Currency
 

Retrieving the data

After creating the table or with a previously created Table, open the dataset with Open method. If the SQL property was not set then all records from all fields will be retrieved, the same if you set the SQL to:

 SQL:='Select * from TABLENAME'; 

Applying changes to the underlying datafile

To use the ApplyUpdates function, the dataset must contain at least one field that fills the requirements for a Primary Key (values must be UNIQUE and not NULL)

It's possible to do that in two ways:

  • Set PrimaryKey property to the name of a Primary Key field
  • Add an AutoInc field (This is easier since the TSqliteDataSet automatically handles it as a Primary Key)

If one of the two conditions is set then just call

 ApplyUpdates;

PS1: If both conditions are set, the field corresponding to PrimaryKey is used to apply the updates.

PS2: Setting PrimaryKey to a field that is not a Primary Key will lead to loss of data if ApplyUpdates is called, so ensure that the chosen field contains not Null and Unique values before using it.

Remarks

  • Although it has been tested with 10000 records and worked fine, TSqliteDataset keeps all the data in memory, so remenber to retrieve only the necessary data (principally with Memo Fields).
  • The same datafile (Filename property) can host several tables/datasets
  • Several datasets (different combinations of fields) can be created using the same table simultaneously
  • It's possible to filter the data using WHERE statements in the sql, closing and reopening the dataset (or calling RefetchData method). But in this case, the order and number of fields must remain the same
  • It's also possible to use complex SQL statements using aliases, joins, views in multiple tables (remember that they must reside in the same datafile), but in this case ApplyUpdates won't work. If someone wants to use complex queries and to apply the updates to the datafile, mail me and I will give some hints how to do that
  • Setting filename to a sqlite2.x datafile not created by TSqliteDataset and opening it is allowed but some fields won't have the correct field type detected. These will be treated as string fields.

Generic examples can be found at fpc/fcl/db/sqlite CVS directory

Luiz Américo pascalive(at)bol(dot)com(dot)br

Lazarus and MSSQL

It is working with Zeoslib (latest cvs), see the links on bottom of page.

Lazarus and Interbase / Firebird

See Install Packages. On this page is a first small example en explanation about how to connect to an IB or FB server.

Also work with the latest Zeoslib (from cvs).

FBLib Firebird Library

[1] is an open Source Library No Data Aware for direct access to Firebird Relational Database from Borland Delphi / Kylix, Freepascal and Lazarus.

Current Features include:

  • Direct Access to Firebird 1.0.x 1.5.x Classic or SuperServer
  • Multiplatform [Win32,Gnu/Linux,FreeBSD)
  • Automatic select client library 'fbclient' or 'gds32'
  • Query with params
  • Support SQL Dialect 1/3
  • LGPL License agreement
  • Extract Metadata
  • Simple Script Parser
  • Only 100-150 KB added into final EXE
  • Support BLOB Fields
  • Export Data to HTML SQL Script
  • Service manager (backup,restore,gfix...)
  • Events Alerter

You can download documentation on FBLib's website.

Lazarus and dBase

Tony Maro

You might also want to visit the beginnings of the TDbf Tutorial page

FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" (TDbf Website) that supports a very basic subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette.

The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine, however it's not the best option for large database applications.

It's very easy to use. Simply, put, drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.

Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.

Attempting to open a non-existant table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.

For instance, to create a table called "dvds" to store your dvd collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".

In your code, insert the following:

   Dbf1.FilePathFull := '/path/to/my/database';
   Dbf1.TableName := 'dvds';
   With Dbf1.FieldDefs do begin
       Add('Name', ftString, 80, True);
       Add('Description', ftMemo, 0, False);
       Add('Rating', ftString, 5, False);
   end;
   Dbf1.CreateTable;

When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data.

Adding indexes is a little different from your typical TTable. It must be done after the database is open. It's also the same method you use to rebuild the indexes. For instance:

   Dbf1.Exclusive := True;
   Dbf1.Open;
   Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);
   Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);
   Dbf1.Close;

The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.

I will try to add a more detailed example at a later date, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!

Related Links

https://trac.synsport.com:8000/index.php/pdo/wiki (username/password is guest/guest)

Contributors and Changes

This page has been converted from the epikwiki version.