Difference between revisions of "Lazarus Database Tutorial/it"

From Lazarus wiki
Jump to navigationJump to search
Line 119: Line 119:
 
=== Connettersi a MySQL da un'Applicazione Lazarus ===
 
=== Connettersi a MySQL da un'Applicazione 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.
+
Questo tutorial mostra come connettere Lazarus a un database MySQL ed eseguire delle semplici interrogazioni, utilizzando solo i componenti di base di Lazarus; non vengono utilizzati componenti Data Aware, ma vengono illustrati i principi dell'interfacciamento con il database.
  
Create a new project in Lazarus:
+
Create un nuovo progetto in Lazarus:
 
  Project -> New Project -> Application
 
  Project -> New Project -> Application
A new automatically generated Form will appear.
+
Apparirà un nuovo form generato automaticamente.
  
Enlarge the form to fill about half of the screen, then re-name the form and its caption to 'TryMySQL'.
+
Ingrandite il form in modo tale che riempia circa metà schermo, quindi rinominate il form e la caption in '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.
+
Dal tab dei componenti Standard posizionate tre Edit Box nella parte in alto a sinistra del Form e, immediatamente sopra ogni box, posizionate una label.  Cambiate name e captions in 'Host' (e HostLLabel, HostEdit), 'UserName' (e UserLabel, UserEdit) e 'Password' (con PasswdLabel e PasswdEdit).  In alternativa potreste utilizzare il componente LabelledEdit dal tab Additional.
  
Select the Passwd Edit box and find the PasswordChar propertychange 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 *sMake sure that the Text property of each edit box is blank.
+
Selezionate l'Edit box Passwd e trovate la proprietà PasswordChar:  cambiatela in '*' o in un altro carattere, in modo che quando digiterete una password i caratteri non appariranno sullo schermo, ma verrà mostrata una serie di *.  Assicuratevi che la proprietà Text di ogni edit box sia vuota.
  
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.
+
Ora posizionate un altro Edit box e un'altra label nell'angolo in alto a destra del form.  Cambiate il testo della label in 'Enter SQL Command' e chiamate l'edit box CommandEdit.
  
Place three Buttons on the form: two on the left under the Edit boxes, and one on the right under the command box.
+
Mettete tre Button sul form: due a sinistra sotto gli Edit box e uno a destra, sotto il command box.
  
Label the buttons on the left 'Connect to Database' (ConnectButton)and 'Exit' (ExitButton) and the one on the right 'Send Query' (QueryButton).
+
Cambiate il testo dei button sulla sinistra in 'Connect to Database' (ConnectButton) e 'Exit' (ExitButton) e il testo di quello a destra in '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.
+
Posizionate un grande Memo Box con una label con il testo 'Results' (ResultMemo) nella parte inferiore destra del form, in modo tale da riempire quasi tutto lo spazio disponibile. Cambiate la proprietà ScrollBars in ssAutoBoth in modo che le scroll bar appaiano automaticamente se il testo riempie lo spazio. Mettete la proprietà WordWrap a True.
  
Place a Status Bar (from the Common Controls tab) at the bottom of the Form, and make its SimpleText property 'TryMySQL'.
+
Posizionate unoa Status Bar (dal tab Common Controls) nella parte bassa del form e cambiate la sua proprietà SimpleText in 'TryMySQL'.
  
A screenshot of the Form can be seen here: [http://lazarus-ccr.sourceforge.net/kbdata/trymysqldb.png Mysql Example Screenshot]
+
Uno screenshot del form può essere visualizzato da qui: [http://lazarus-ccr.sourceforge.net/kbdata/trymysqldb.png Mysql Example Screenshot]
  
Now we need to write some event handlers.
+
Ora abbiamo bisogno di scrivere alcuni 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 clickedThe OnCLick event handler for this button is based on part of the text-mode FPC program above.
+
I tre Edit box sulla sinistra serviranno per immettere hostname, username e password.  Quando sono stati inseriti, viene premuto il tasto Connect.  L'evento OnCLick del button è basato su parte del programma FPC in modalità testuale appena visto.
  
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.   
+
Le risposte dal database ora non possono essere scritte con l'ausilio dei comandi pascal write o writeln: piuttosto, le risposte devono essere convertite in string e mostrate nel Memo box.  Laddove i comandi Pascal write e writeln sono in grado di effettuare diverse conversioni di tipo 'al volo', l'utilizzo di una memo box per l'output di testo necessita di una conversione esplicita dei tipi di dato in string, così le variabili di tipo Pchar devono essere convertite in string mediante StrPas, gli integer tramite IntToStr.   
  
Strings are displayed in the Memo box using
+
Le string vengono mostrate nel Memo box tramite l'utilizzo di
  
 
  procedure ShowString (S : string);
 
  procedure ShowString (S : string);
Line 157: Line 157:
 
  end;
 
  end;
  
The ConnectButton event handler thus becomes:
+
Così l'evento onClick del ConnectButtondiventa:
  
 
  procedure TtrymysqlForm1.ConnectButtonClick(Sender: TObject);
 
  procedure TtrymysqlForm1.ConnectButtonClick(Sender: TObject);
 
  (* Connect to MySQL using user data from Text entry boxes on Main Form *)
 
  (* Connect to MySQL using user data from Text entry boxes on Main Form *)
  var strg: string;
+
  var  
 
+
  strg: string;
 
  begin
 
  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];
 
    
 
    
  dummy1 :=  trymysqlForm1.HostEdit.text+#0;
+
  alloc := mysql_init(PMYSQL(@qmysql));
  host := @dummy1[1];
+
  sock :=  mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
  dummy2 := trymysqlForm1.UserEdit.text+#0;
+
  if sock=Nil then
  user := @dummy2[1] ;
+
  begin
  dummy3 := trymysqlForm1.PasswdEdit.text+#0;
+
    strg :='Couldn''t connect to MySQL.'; showstring (strg);
  passwd := @dummy3[1] ;
+
    Strg :='Error was: '+ StrPas(mysql_error(@qmysql)); showstring (strg);
 
+
   end else
  alloc := mysql_init(PMYSQL(@qmysql));
+
  begin
  sock :=  mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
+
    trymysqlForm1.statusBar1.simpletext := 'Connected to MySQL';
  if sock=Nil then
+
    strg := 'Now choosing database : ' + database; showstring (strg);
    begin
+
  {$ifdef Unix}
      strg :='Couldn''t connect to MySQL.'; showstring (strg);
+
    strg :='Mysql_port      : '+ IntToStr(mysql_port); showstring (strg);
      Strg :='Error was: '+ StrPas(mysql_error(@qmysql)); showstring (strg);
+
    strg :='Mysql_unix_port : ' + StrPas(mysql_unix_port); showstring (strg);
   end
+
  {$endif}
    else
+
    Strg :='Host info      : ' + StrPas(mysql_get_host_info(sock));
    begin
+
    showstring (strg);
      trymysqlForm1.statusBar1.simpletext := 'Connected to MySQL';
+
    Strg :='Server info    : ' + StrPas(mysql_stat(sock)); showstring (strg);
      strg := 'Now choosing database : ' + database; showstring (strg);
+
    Strg :='Client info    : ' + Strpas(mysql_get_client_info);  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 +'...';
+
    trymysqlForm1.statusbar1.simpletext := 'Selecting Database ' + DataBase +'...';
  if mysql_select_db(sock,DataBase) < 0 then
+
    if mysql_select_db(sock,DataBase) < 0 then
  begin
+
    begin
    strg :='Couldn''t select database '+ Database; ShowString (strg);
+
      strg :='Couldn''t select database '+ Database; ShowString (strg);
    Strg := mysql_error(sock); ShowString (strg);
+
      Strg := mysql_error(sock); ShowString (strg);
  end
+
    end
  end;
+
  end;
 
  end;
 
  end;
  

Revision as of 14:17, 21 June 2008

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)

Panoramica

Questo tutorial è incentrato sul funzionamento di Lazarus con una serie di database esistenti.

Lazarus supporta di base diversi database; in ogni caso lo sviluppatore deve installare il package adeguato per ciascuno di essi. E' possibile accedere al database attraverso il codice oppure disponendo dei componenti su un form. I componenti data-aware rappresentano i campi del database e vengono collegati impostando la proprietà DataSource in modo che punti ad un TDataSource. Il Datasource rappresenta una table ed è collegato ai componenti del database (per esempio: TPSQLDatabase, TSQLiteDataSet) impostando la proprietà DataSet. I componenti data-aware sono situati nel tab "Data Controls" della palette dei componenti di Lazarus. Il componente Datasource e i componenti dei database sono situati nel tab "Data Access".

Lazarus e MySQL

Far funzionare MySQL su Linux o Windows

Seguite le istruzioni riportate sul MySQL User Manual. Assicuratevi che il daemon mysqld giri correttamente e che tutti i potenziali utenti (inclusi root, mysql, voi stessi e ognuno che ne abbia bisogno) abbiano i privilegi di cui necessitano, da tutti gli host richiesti (inclusi 'localhost', il nome dell'host locale, qualsiasi altro host della vostra rete) per quanto sia consistente con la sicurezza. E' preferibile che tutti gli utenti, incluso il root, abbiano una password. Controllate il funzionamento del sistema del database utilizzando l'esempio fornito nel manuale e assicuratevi che tutti gli utenti abbiano realmente accesso al database.

Far funzionare MySQL con FPC in modalità testuale

C'è una directory con un programma di esempio in $(fpcsrcdir)/packages/base/mysql/. Potete trovare la directory dei sorgenti del fpc in Lazarus: Environment menu -> Environment Options -> Paths tab -> FPC source directory. Alcuni percorsi tipici per la directory di mysql sono /usr/share/fpcsrc/packages/base/mysql/ (rpm install) oppure C:\lazarus\fpcsrc\packages\base\mysql\ (windows). Questa directory contiene anche le units mysql.pp, mysql_com.pp e mysql_version.pp. Prima di avviare lo script per il test, avrete bisogno di creare un database chiamato testdb: è possibile fare ciò loggandosi nel monitor mysql (come root con pieni privilegi) e immettendo la seguente linea SQL

CREATE DATABASE testdb;

quindi assicurandovi che tutti gli utenti abbiano i privilegi di accesso appropriati

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

Esiste uno script chiamato mkdb che ora dovreste provare a lanciare:

sh ./mkdb

Probabilmente restituirà un errore, poiché il sistema non permette ad utenti anonimi di accedere al database. Quindi modificate lo script utilizzando un editor di testo in modo tale che la linea che chiama mysql sia:

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

e provate a lanciarlo di nuovo, immettendo la vostra password quando richiesto. Con un pizzico di fortuna dovreste essere in grado di creare il database di test: provatelo (loggati nel monitor mysql) lanciando la sequenza di comandi mysql

select * from FPdev;

Dovreste vedere una tabella contenente l'ID, lo username e l'indirizzo email di alcuni degli sviluppatori del FPC.

Ora provate a lanciare il programma di test testdb.pp (potrebbe essere necessario compilarlo, e quasi sicuramente non andrà a buon fine al primo tentativo!!).

Ho scoperto che il programma potrebbe non connettersi a mysql per diverse ragioni:

  • Il mio sistema (SuSE Linux v9.0) installa mysql v4.0.15, non la versione 3 per la quale il package è stato disegnato.
  • Il programma ha bisogno di avere nome utente e password per accedere al database.
  • Il compilatore ha bisogno di sapere dove trovare le librerie di mysql (NEL CASO IN CUI NON ABBIATE PROVVEDUTO AD INSTALLARE LE LIBRERIE DI SVILUPPO DI MYSQL, FATELO ORA!)

Ho creato una copia di testdb.pp chiamandola trydb.pp, piuttosto che modificare l'originale - questo significa che i files originali verranno ancora corretti durante gli aggiornamenti successivi da CVS. Ho anche cpiato i files trovati nella sottodirectory mysql/ver40/ nella sottodirectory principale mysql/, rinominandoli mysql_v4.pp, mysql_com_v4.pp e mysql_version_v4.pp, assicurandomi di rinominare le units all'interno di ogni file in maniera corrispondente. Ho cambiato il blocco uses in trydb.pp in

uses mysql_v4

e quello in mysql_v4.pp in

uses mysql_com_v4

Ho aggiunto una linea a /etc/fpc.cfg per far puntare il compilatore alle mie librerie:

-Fl/lib;/usr/lib

I passi seguenti potrebbero non essere necessari se le librerie di sviluppo sono state installate, poiché i collegamenti vengono creati automaticamente, ma controllare non fa mai male. Ho dovuto trovare il vero nome della libreria mysqlclint in /usr/lib e, nel mio caso, ho dovuto lanciare il comando da shell:

ln -s libmysqlclient.so.12.0.0 lmysqlclient

per creare un link simbolico che permettesse a FPC di trovare la libreria. Per buona pratica ho anche creato il link

ln -s libmysqlclient.so.12.0.0 mysqlclient

e posizionato link simili in altre directory: non strettamente necessario, solo per sicurezza...! Alcuni utenti potrebbero aver bisogno di aggiungere il seguente link:

ln -s libmysqlclient.so.12.0.0 libmysqlclient.so

Ho modificato trydb.pp in modo da includere i dettagli dell'utente, inizialmente aggiungendo l'host, l'user e la password come costanti:

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

Ho anche scoperto che non posso connettermi a mysql utilizzando mysql_connect(), ma ho dovuto utilizzare mysql_real_connect() che ha molti più parametri. Per complicare le cose ulteriormente il numero di parametri sembra essere cambiato tra la versione 3 (dove erano sette) e la versione 4 (dove sono otto). Prima di utilizzare mysql_real_connect ho dovuto utilizzare mysql_init() che non esiste nel file mysql.pp originale, ma esiste in mysql_v4.pp.

Quindi il codice per la connessione al database è:

{ a few extra variables}
var
  alloc : PMYSQL;
 
{main program fragment}
 
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}


Ora siete pronti per compilare trydb.pp?

 fpc trydb

fatto! Adesso lanciatelo:

 ./trydb

whoopee! Ho ottenuto l'elenco degli sviluppatori del FPC!

Alcuni ulteriori perfezionamenti: rendete interattive l'immissione dei dettagli dell'utente e l'immissione dei comandi, utilizzando variabili piuttosto che costanti, e permettete di inserire diversi comandi SQL, finché non viene rovato il comando quit: controllate il listato completo del programma, dove i dettagli dell'utente sono inseriti da console, e il programma va in un loop dove i comandi SQL sono inseriti sempre da console (senza il punto e virgola finale) e le risposte vengono mostrate a schermo solo quando 'quit' viene inserito dalla tastiera.

Vedi Sample Console Listing.

Connettersi a MySQL da un'Applicazione Lazarus

Questo tutorial mostra come connettere Lazarus a un database MySQL ed eseguire delle semplici interrogazioni, utilizzando solo i componenti di base di Lazarus; non vengono utilizzati componenti Data Aware, ma vengono illustrati i principi dell'interfacciamento con il database.

Create un nuovo progetto in Lazarus:

Project -> New Project -> Application

Apparirà un nuovo form generato automaticamente.

Ingrandite il form in modo tale che riempia circa metà schermo, quindi rinominate il form e la caption in 'TryMySQL'.

Dal tab dei componenti Standard posizionate tre Edit Box nella parte in alto a sinistra del Form e, immediatamente sopra ogni box, posizionate una label. Cambiate name e captions in 'Host' (e HostLLabel, HostEdit), 'UserName' (e UserLabel, UserEdit) e 'Password' (con PasswdLabel e PasswdEdit). In alternativa potreste utilizzare il componente LabelledEdit dal tab Additional.

Selezionate l'Edit box Passwd e trovate la proprietà PasswordChar: cambiatela in '*' o in un altro carattere, in modo che quando digiterete una password i caratteri non appariranno sullo schermo, ma verrà mostrata una serie di *. Assicuratevi che la proprietà Text di ogni edit box sia vuota.

Ora posizionate un altro Edit box e un'altra label nell'angolo in alto a destra del form. Cambiate il testo della label in 'Enter SQL Command' e chiamate l'edit box CommandEdit.

Mettete tre Button sul form: due a sinistra sotto gli Edit box e uno a destra, sotto il command box.

Cambiate il testo dei button sulla sinistra in 'Connect to Database' (ConnectButton) e 'Exit' (ExitButton) e il testo di quello a destra in 'Send Query' (QueryButton).

Posizionate un grande Memo Box con una label con il testo 'Results' (ResultMemo) nella parte inferiore destra del form, in modo tale da riempire quasi tutto lo spazio disponibile. Cambiate la proprietà ScrollBars in ssAutoBoth in modo che le scroll bar appaiano automaticamente se il testo riempie lo spazio. Mettete la proprietà WordWrap a True.

Posizionate unoa Status Bar (dal tab Common Controls) nella parte bassa del form e cambiate la sua proprietà SimpleText in 'TryMySQL'.

Uno screenshot del form può essere visualizzato da qui: Mysql Example Screenshot

Ora abbiamo bisogno di scrivere alcuni event handlers.

I tre Edit box sulla sinistra serviranno per immettere hostname, username e password. Quando sono stati inseriti, viene premuto il tasto Connect. L'evento OnCLick del button è basato su parte del programma FPC in modalità testuale appena visto.

Le risposte dal database ora non possono essere scritte con l'ausilio dei comandi pascal write o writeln: piuttosto, le risposte devono essere convertite in string e mostrate nel Memo box. Laddove i comandi Pascal write e writeln sono in grado di effettuare diverse conversioni di tipo 'al volo', l'utilizzo di una memo box per l'output di testo necessita di una conversione esplicita dei tipi di dato in string, così le variabili di tipo Pchar devono essere convertite in string mediante StrPas, gli integer tramite IntToStr.

Le string vengono mostrate nel Memo box tramite l'utilizzo di

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

Così l'evento onClick del ConnectButtondiventa:

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

Scaricare il codice sorgente MYSQL

Un listato completo del programma è disponibile qui: Sample Source Code

Lazarus e PostgreSQL

Questa è una guida molto breve che spiega come connettere Lazarus 0.9.12 o successivo a un database PostgreSQL, locale o remoto, tramite l'utilizzo di TPQConnection.

Dopo avere correttamente installato il package, seguite questi passi:

  • Posizionare un PQConnection dal tab SQLdb
  • Posizionare un SQLQuery dal tab SQLdb
  • Posizionare un SQLTransaction dal tab SQLdb
  • Posizionare un DataSource dal tab DataAccess
  • Posizionare un DBGrid dal tab DataControls
  • In PQConnection modificare le proprietà:
    • transaction con il rispettivo oggetto SQLTransaction
    • Database name
    • HostName
    • UserName + password
  • Assicurarsi che SQLTransaction sia cambiato automaticamente per puntare a PQConnection
  • In SQLQuery modificare le proprietà:
    • transaction con il rispettivo oggetto
    • database con il rispettivo oggetto
    • SQL (qualcosa del tipo 'select * from anytable')
  • Nell'oggetto DataSource assegnate alla proprietà DataSet l'oggetto SQLQuery
  • In DBGrid assegnate alla proprietà datasource l'oggetto DataSource

Posizionare tutti gli switch su connected e active e la DBGrid dovrebbe essere riempita a design time. TDBText e TDBEdit sembrano funzionare, ma (per me) _mostrano_ _dati_ solamente.

Per cambiare i contenuti nel database, ho chiamato direttamente il motore DB con il seguente codice:

 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;


  • Note:
    • Controllato su windows, Lazarus 0.9.12 + PgSQL 8.3.1
    • Alcune prove su linux, Lazarus 0.9.12 and PgSQL 8.0.x


  • Installazione e errori:
    • Nella verione .12 di Lazarus che ho provato, i campi del tipo "text" e "numeric" hanno dei bugs
    • Ho usato senza problemi char fixed size, int e float8
    • Alcune volte riavviare Lazarus risolve stupidi errori...
    • Dopo alcuni errori, le transaczioni rimangono attive e devono essere disattivate a mano
    • Le modifiche fatte in Lazarus ovviamente non sono visibili finché la transazione non viene passata
    • Il debugger integrato sembra buggato (almeno in windows) - alcune volte far girare l'eseguibile fuori dall'ide può aiutare a scovare errori
    • In linux alcuni messaggi d'errore vengono mostrati nella console -- lanciate il vostro programma da linea di comando, alcune volte ci sono ulteriori informazioni di debug molto utili
    • Error: "Can not load Postgresql client. Is it installed (libpq.so) ?"
      • Aggiungete il percorso per trovare libpq* dall'installazione di PostgreSQL.
      • In linux aggiungete il percorso per trovare il file libpq.so alla sezione delle librerie nel vostro file /etc/fpc.cfg. Per esempio: -Fl/usr/local/pgsql/lib
      • In windows, aggiungete queste librerie dove volete, in una directory indicata nella variabile d'ambiente Path o nella directory del progetto
      • In windows, ho copiato tutte le dll presenti in C:\Program Files\PostgreSQL\8.1\bin in un'altra directory segnata in PATH
      • Oppure aggiungete la directory postgres\bin al path

Lazarus e SQLite

by Luiz Américo

Visit the sqlite4fpc homepage to find the API reference and more tutorials.

Introduzione

TSqliteDataset and TSqlite3Dataset are TDataset descendants that access, respectively, 2.8.x and 3.x.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 installation/configuration: just ship together with sqlite dynamic library

Disadvantages

  • Requires external file (sqlite library)

Requisiti

  • 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

Come utilizzare SQLite (utilizzo di base)

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.

Note

  • Although it has been tested with 10000 records and worked fine, TSqliteDataset keeps all the data in memory, so remember 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 e MSSQL

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

Lazarus e 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).

Libreria FBLib per Firebird

[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 e 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. Note: Current version of OpenOffice (2.0x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.

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!


Ricerca e Visualizzazione di un insieme di dati

Simon Batty

In this example I wanted to search a database of books for all the titles an author has listed and then display the list in a memo box


   Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory
   Dbf1.TableName := 'books.dbase';                             // database file (including extension)
   DbF1.Open;
   memo1.Clear;                                                 // clear the memo box
   Dbf1.FilterOptions := [foCaseInsensitive];
   Df1.Filter := 'AU=' + QuotedStr('anauthor');         // AU is the field name containing the authors
   Dbf1.Filtered := true;       // This selects the filtered set
   Dbf1.First;                  // moves the the first filtered data
   while not dbf1.EOF do        // prints the titles that match the author to the memo box
   begin
       memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles
       dbf1.next;                                     // use .next here NOT .findnext!
   end;
   Dbf1.Close;   

Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang.

This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.

Altri Links

Contributi e Modifiche

Questa pagina è stata convertita dalla versione di epikwiki.