Difference between revisions of "postgres/fr"

From Lazarus wiki
Jump to navigationJump to search
Line 27: Line 27:
  
 
==SQLDB==
 
==SQLDB==
FPC/Lazarus supports PostgreSQL out of the box with a PostgreSQL connection component/class. If you are using FPC only or want to manually add PostgreSQL support, add ''pqconnection'' to your ''uses'' clause. Otherwise, Lazarus provides a component:
+
FPC / Lazarus prend en charge PostgreSQL avec un composant/classe de connexion PostgreSQL. Si vous utilisez FPC seulement ou voulez ajouter manuellement la prise en charge de PostgreSQL, ajoutez ''pqconnection'' à votre clause ''uses''. Autrement, Lazarus fournit le composant :
  
 
[[Image:sqldbcomponents.png‎]]
 
[[Image:sqldbcomponents.png‎]]
  
'''Note:''' The libpq C client contains some memory leaks (at least up till version 9.3 of Postgres) when a library is repeatedly loaded/unloaded.
+
'''Note :''' la bibliothèque cliente C libpg contient quelques fuites de mémoires (au moins jusqu'à la version 9.3 de Postgres) quand une bibliothèque est chargée/déchargée de manière répétitive. SQLdb charge la bibliothèque à la première connexion, et la décharge à la dernière. Cela signifie que chaque fois que la dernière connexion est fermée, une petite fuite de mémoire est créée. Pour empêcher cela d'arriver (et accélérer l'application), vous pouvez charger le, vous pouvez charger la bibliothèque une fois au démarrage du processus avec l'appel à InitialisePostgres3.
SQLDB loads the library when the first connection is made, and unloads it when the last connection closes. This means that whenever the last
 
connection is closed, a small memory leak is created. To prevent this from happening (and speed up the application), you can load the
 
library once at the start of the process with the InitialisePostgres3 call.
 
  
The charset property is used for client encoding.
+
La propriété charset est utilisée pour l'encodage du client.
  
The TPQConnection component does not directly support a Port property, but one can pass the port into the component via the Params parameter:
+
Le composant TPQConnection ne prend pas en charge directement une propriété Port, on peut passer le port dans le composant via le paramètre Params :  
  
 
<syntaxhighlight>PQConnection.Params.Add('port=' + VariableContainingPort);</syntaxhighlight>
 
<syntaxhighlight>PQConnection.Params.Add('port=' + VariableContainingPort);</syntaxhighlight>
  
Other PostgreSQL specific connection parameters can be specified using the Params property:
+
D'autres paramètres de connexion particuliers peuvent être spécifiés en utilisant la propriéét Params :
 +
 
 
<syntaxhighlight>PQConnection.Params.Add('application_name=''yourappname''')</syntaxhighlight>
 
<syntaxhighlight>PQConnection.Params.Add('application_name=''yourappname''')</syntaxhighlight>
  
 
===Exemple===
 
===Exemple===
See [[SQLdb_Tutorial1]] for a tutorial on creating a GUI database-enabled program that is written for PostgreSQL/SQLDB, as well as SQLite/SQLDB, Firebird/SQLDB, basically any RDBMS SQLDB supports).
+
Voir See [[SQLdb_Tutorial1/fr|Tutoriel SQLdb 1]] pour un tutoriel sur la création d'une application de base de données avec IHM écrite avec PostgreSQL/SQLdb, aussi bien qu'avec SQLite/SQLDB, Firebird/SQLDB ou basiquement avec toute base de données prise en charge par SQLDB.
  
 
=== Surveillance des événements ===
 
=== Surveillance des événements ===
If you have FPC2.6.2+ and a recent version of Lazarus, you can use the '''TPQTEventMonitor''' component to monitor events coming from PostgreSQL.  
+
Si vous avez FPC 2.6.2+ et une version récente de Lazarus, vous pouvez utiliser le composant '''TPQTEventMonitor''' pour surveiller les événements venant de PostgreSQL.
  
It is a thin wrapper around FPC '''PQEventMonitor'''; please see the FPC pqeventstest.pp example programs for details.
+
C'est une enveloppe mince autour de FPC '''PQEventMonitor''' ; veuillez consulter le programme exemple FPC pqeventstest.pp pour les détails.
  
 
=== Installation et erreurs ===
 
=== Installation et erreurs ===
As with all sqldb units, you need to add your driver libraries ('''all''' required PostgreSQL .dll/.manifest files)
+
Comme pour toutes les unités SQLdb, vous avez besoin de vos bibliothèque cliente ('''tous''' les fichiers PostgreSQL .dll/.manifest)
* to a directory in the (library search) path (e.g. c:\windows\system32 for Windows)
+
* dans une dossier dans le chemin (de recherche des bibliothèques, tel que c:\windows\system32 pour Windows)
* or (Windows) to the program output directory (e.g. lib/something/ in your project directory, and the project directory
+
* ou (pour Windows) dans le dossier de votre programme (p.ex. lib\something\ dans votre dossier de projet et le
  
 
==== Pilote Windows 64 bit ====
 
==== Pilote Windows 64 bit ====

Revision as of 07:36, 3 May 2017

Deutsch (de) English (en) español (es) français (fr)

Portail de la base de données

Références:

Tutoriels/articles pratiques :

Bases de données

Advantage - MySQL - MSSQL - Postgres - Interbase - Firebird - Oracle - ODBC - Paradox - SQLite - dBASE - MS Access - Zeos

Vue d'ensemble

Vous pouvez utiliser Free Pascal/Lazarus pour accéder à un serveur de base de données PostgreSQL. Si vous cherchez de l'information sur le paquet postgres dans FPC, veuillez consulter #Paquet PostgreSQL : les unités de bas-niveau plus bas.

Avantages de PostgreSQL:

  • Il est disponible et largement utilisé
  • Très stable et a un ensemble complet de fonctionnalités.
  • Licence libérale (sans frais) par rapport à MySQL.

Inconvénient de PostgreSQL:

  • Certains hébergeurs peuvent ne pas offrir PostgreSQL
  • Pas de version incorporée (i.e. sans serveur distant/installé, comme Firebird le propose)

Win64: SVP, consulter l'avertissement ici sur l'inutilisation de certaines versions de FPC/Lazarus Win64.

Accès direct à PostgreSQL

Vous pouvez vous connecter à PostgreSQL avec Lazarus en utilisant les composants PostgreSQL Data Access (PgDAC). C'est une bibliothèque de composants qui fournissent une connectivité native à PostgreSQL depuis Lazarus (et Free Pascal) sur Windows, Mac OS X, iOS, Android, Linux et FreeBSD pour les plates-formes 32-bit et 64-bit. PgDAC est conçue pour aider le programmeur à développer des applications PostgreSQL réellement légères, rapides et propres sans déploiement de bibliothèques supplémentaires.

Vous pouvez la télécharger librement depuis Composants Lazarus.

Zeos

Zeos prend en charge PostgreSQL ; veuillez lire ZeosDBO.

SQLDB

FPC / Lazarus prend en charge PostgreSQL avec un composant/classe de connexion PostgreSQL. Si vous utilisez FPC seulement ou voulez ajouter manuellement la prise en charge de PostgreSQL, ajoutez pqconnection à votre clause uses. Autrement, Lazarus fournit le composant :

sqldbcomponents.png

Note : la bibliothèque cliente C libpg contient quelques fuites de mémoires (au moins jusqu'à la version 9.3 de Postgres) quand une bibliothèque est chargée/déchargée de manière répétitive. SQLdb charge la bibliothèque à la première connexion, et la décharge à la dernière. Cela signifie que chaque fois que la dernière connexion est fermée, une petite fuite de mémoire est créée. Pour empêcher cela d'arriver (et accélérer l'application), vous pouvez charger le, vous pouvez charger la bibliothèque une fois au démarrage du processus avec l'appel à InitialisePostgres3.

La propriété charset est utilisée pour l'encodage du client.

Le composant TPQConnection ne prend pas en charge directement une propriété Port, on peut passer le port dans le composant via le paramètre Params :

PQConnection.Params.Add('port=' + VariableContainingPort);

D'autres paramètres de connexion particuliers peuvent être spécifiés en utilisant la propriéét Params :

PQConnection.Params.Add('application_name=''yourappname''')

Exemple

Voir See Tutoriel SQLdb 1 pour un tutoriel sur la création d'une application de base de données avec IHM écrite avec PostgreSQL/SQLdb, aussi bien qu'avec SQLite/SQLDB, Firebird/SQLDB ou basiquement avec toute base de données prise en charge par SQLDB.

Surveillance des événements

Si vous avez FPC 2.6.2+ et une version récente de Lazarus, vous pouvez utiliser le composant TPQTEventMonitor pour surveiller les événements venant de PostgreSQL.

C'est une enveloppe mince autour de FPC PQEventMonitor ; veuillez consulter le programme exemple FPC pqeventstest.pp pour les détails.

Installation et erreurs

Comme pour toutes les unités SQLdb, vous avez besoin de vos bibliothèque cliente (tous les fichiers PostgreSQL .dll/.manifest)

  • dans une dossier dans le chemin (de recherche des bibliothèques, tel que c:\windows\system32 pour Windows)
  • ou (pour Windows) dans le dossier de votre programme (p.ex. lib\something\ dans votre dossier de projet et le

Pilote Windows 64 bit

If you are developing 64 bit applications, you must use a 64 bit DLL.

Light bulb  Remarque: FPC 2.6.0 (therefore Lazarus 1.0.4 or lower) does not yet support PostgreSQL on Windows 64 bit (unless you patch and recompile it).

A Windows 64 driver is fairly hard to find but can be downloaded here: [1]. The driver library can be installed in c:\windows\system32; 32 bit driver libraries can be installed in the confusingly named c:\windows\syswow64

Erreur: "Can not load PostgreSQL client library "libpq.dll""

The program cannot find your PostgreSQL driver files.

See above on instructions where to install the libraries.

A good example that demonstrates how to include drive DLL files when connecting Lazarus with PostgreSQL under Windows is easyDB.

On Linux/Unix/OSX: make sure the PostgreSQL libraries are in your library search path, e.g.:

  • On 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
  • It may be necessary to create a symbolic link from a specific library version to a general library name:
    ln -s /usr/lib/pqsql.so.5 /usr/lib/pqsql.so
    
    . Alternatively, install the postgresql client -dev package using your distribution's package manager

Problèmes de nettoyage des paramètres

Light bulb  Remarque: Verify this: is .paramtype really necessary?

At least in FPC <= 2.6.2: if you .Clear a parameter (i.e. set it to NULL), PostgreSQL may have difficulty recognizing the parameter type.

In that case, explicitly specify the type, e.g.:

FWriteQuery.Params.ParamByName('LONGITUDE').ParamType:=ptInput; //required for postgresql
FWriteQuery.Params.ParamByName('LONGITUDE').Clear

Comment faire

Utiliser INSERT RETURNING

Obtenir le dernier ID inséré

With PostGres there is no need to run a second query to get the last inserted ID.

Use INSERT RETURNING and read the value:

var 
  ID: Integer
..
Query.SQL.Text:= 'INSERT INTO myschema.films(film_name)' +
                 'VALUES(:film_name) RETURNING film_id;';
Query.Open;
ID:= Query.FieldByName('film_id').AsInteger;

Obtenir des champs multiples et des expressions

RETURNING in PostgreSQL is more flexible than most database engines. It works with INSERT, UPDATE, and DELETE statements and can be any list of fields, constants, or expressions that would be found in a SELECT list.

INSERT INTO films (film_name) VALUES ('val') RETURNING film_id;  -- Returns id's for newly created rows.
INSERT INTO films (film_name) VALUES ('val') RETURNING film_id, kind;  -- Returns id and kind fields in newly created rows.
INSERT INTO films (film_name) VALUES ('val') RETURNING *; -- Returns all fields in newly created rows.
     
UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama' RETURNING film_id; -- Returns id's of updated rows.
UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama' RETURNING film_id, film_name; -- Returns id and film names of updated rows.
UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama' RETURNING *; -- Returns all fields of updated rows.
     
DELETE FROM films RETURNING film_id; --Returns id's of deleted rows.
DELETE FROM films RETURNING film_id, film_name; --Returns id's and film names of deleted rows.
DELETE FROM films RETURNING *;  -- Returns all fields of deleted rows.

RETURNING using fields, constants, and expressions:

INSERT INTO films (film_name) VALUES ('val') RETURNING id, 'a' AS a, id*2 AS doubled_id, CASE WHEN id > 100 THEN 'a' ELSE 'b' END AS foo;

Paquet PostgreSQL : les unités de bas-niveau

As with all databases, the SQLDB code depends on a lower level PostgreSQL specific unit that wraps around the PostgreSQL driver library (.so/.dll/.dylib). Normally, you would use the higher-level SQLDB code as it allows you to code more quickly, easily switch databases etc.

Using this is very easy, all you need to do is compile some units, and use these units in your program. You need to specify the place of the PostgreSQL client Library (libpq) when compiling, and that is it.

The main unit is called postgres, normally this is the only unit you must include in your uses clause.

Exigences

You need at least version 0.99.5 of Free Pascal (basically any version of FPC except extremely old ones). The headers are translated from PostgreSQL version 6.3.1.

Installation

The postgres unit comes with the Free Pascal packages, and is distributed together with the compiler. This contains a directory postgres with the units, a test program and a makefile. cd to the directory and edit the Makefile to set the variables for your system. You must provide only 1 thing:

  1. The directory where the libpq library resides, usually /usr/local/pgsql/lib

Typing

make

Should compile the units and the program. If compilation was succesfull, you can install with

make install

(Remember to set the directory where the units should be installed.)

You can then test the program by running

make test

This will:

  • Run the test program testpg. It is a straightforward pascal translation of the example program in the PostGreSQL programmers' guide.
  • Run a script to create a table in a database, and fill it with some data. (the psql program should be in your PATH for this) . By default, the used database is testdb.
  • Run the testprogram testemail
  • Run a shell script again to remove the created table.

You will see a lot of messages on your screen, giving you feedback and results. If something went wrong, make will inform you of this.

Go back to Packages List

Voir aussi

  • TPSQL - Un ensemble de composants dataset/database pour PostgreSQL alternatif.
  • Lazarus DB Faq - Plus d'info sur la programmation des SGBDR.
  • Lazarus Database Tutorial - Faire travailler Lazarus avec diverses bases de données.