Difference between revisions of "SQLdb Tutorial1/es"

From Free Pascal wiki
Jump to navigationJump to search
(error en categoría)
 
(8 intermediate revisions by 3 users not shown)
Line 1: Line 1:
{{SQLdb Tutorial}}
+
{{SQLdb Tutorial1}}
 +
 
 
== Introducción ==
 
== Introducción ==
  
 
Este tutorial muestra como programar con bases de datos (BBDD) utilizando un ejemplo práctico basado en el [[SQLdb Package|paquete SQLdb]]. Está primordialmente orientado a principiantes. Para quien esté buscando sobre fundamentos de bases de datos SQL debería leer libros y documentación relevante.
 
Este tutorial muestra como programar con bases de datos (BBDD) utilizando un ejemplo práctico basado en el [[SQLdb Package|paquete SQLdb]]. Está primordialmente orientado a principiantes. Para quien esté buscando sobre fundamentos de bases de datos SQL debería leer libros y documentación relevante.
Para este tutorial he utilizado Firebird con el fichero de bases de dato ejempo llamado employee.fdb. Se pueden utilizar otras bases de datos, para lo cual se requieren algunos ajustes que se mencionan en este texto.
+
Para este tutorial he utilizado Firebird con el fichero de bases de datos ejempo llamado employee.fdb. Se pueden utilizar otras bases de datos, para lo cual se requieren algunos ajustes que se mencionan en este texto.
 
   
 
   
 
Mientras que este tutorial puede parecer muy extenso, sin embargo es simplemente una explicación ajustada de lo que hay que teclear y porque. Como podrás deducir al final, la cantidad de código actual que se necesitará para tener una aplicación funcional no es tan grande. La mayor parte de los desarrolladores experimentados serán felizmente capaces de recorrer el código y entender de que trata.
 
Mientras que este tutorial puede parecer muy extenso, sin embargo es simplemente una explicación ajustada de lo que hay que teclear y porque. Como podrás deducir al final, la cantidad de código actual que se necesitará para tener una aplicación funcional no es tan grande. La mayor parte de los desarrolladores experimentados serán felizmente capaces de recorrer el código y entender de que trata.
Line 34: Line 35:
 
Extraer estos ficheros en el directorio de la aplicación:
 
Extraer estos ficheros en el directorio de la aplicación:
  
<syntaxhighlight lang="bash">
+
<syntaxhighlight lang="bash"> fbembed.dll
fbembed.dll
+
firebird.msg
firebird.msg
+
ib_util.dll
ib_util.dll
+
icudt30.dll
icudt30.dll
+
icuin30.dll
icuin30.dll
+
icuuc30.dll
icuuc30.dll
+
Microsoft.VC80.CRT.manifest
Microsoft.VC80.CRT.manifest
+
msvcp80.dll
msvcp80.dll
+
msvcr80.dll</syntaxhighlight>
msvcr80.dll
 
</syntaxhighlight>
 
  
 
Renombrar fbembed.dll a fbclient.dll (el nombre regular para el cliente de Firebird cliente-servidor - esto ayuda a utilizarlo en versiones antiguas de Lazarus/FPC). La librería DLL embebida de Firebird puede actuar como un cliente regular de Firebird.
 
Renombrar fbembed.dll a fbclient.dll (el nombre regular para el cliente de Firebird cliente-servidor - esto ayuda a utilizarlo en versiones antiguas de Lazarus/FPC). La librería DLL embebida de Firebird puede actuar como un cliente regular de Firebird.
Line 65: Line 64:
 
Creamos una tabla llamada EMPLOYEE que será utilizada en un tutorial posterior.
 
Creamos una tabla llamada EMPLOYEE que será utilizada en un tutorial posterior.
  
<syntaxhighlight lang="sql">
+
<syntaxhighlight lang="sql"> CREATE TABLE CUSTOMER
CREATE TABLE CUSTOMER
+
(
(
+
  CUST_NO INTEGER NOT NULL,
  CUST_NO INTEGER NOT NULL,
+
  CUSTOMER VARCHAR(25) NOT NULL,
  CUSTOMER VARCHAR(25) NOT NULL,
+
  CITY VARCHAR(25),
  CITY VARCHAR(25),
+
  COUNTRY VARCHAR(15),
  COUNTRY VARCHAR(15),
+
  CONSTRAINT CT_CUSTOMER_PK PRIMARY KEY (CUST_NO)
  CONSTRAINT CT_CUSTOMER_PK PRIMARY KEY (CUST_NO)
+
);</syntaxhighlight>
);
 
</syntaxhighlight>
 
  
<syntaxhighlight lang="sql">
+
<syntaxhighlight lang="sql"> CREATE TABLE EMPLOYEE
CREATE TABLE EMPLOYEE
+
(
(
+
  EMP_NO INTEGER NOT NULL,
  EMP_NO INTEGER NOT NULL,
+
  FIRST_NAME VARCHAR(15) NOT NULL,
  FIRST_NAME VARCHAR(15) NOT NULL,
+
  LAST_NAME VARCHAR(20) NOT NULL,
  LAST_NAME VARCHAR(20) NOT NULL,
+
  PHONE_EXT VARCHAR(4),
  PHONE_EXT VARCHAR(4),
+
  JOB_CODE VARCHAR(5) NOT NULL,
  JOB_CODE VARCHAR(5) NOT NULL,
+
  JOB_GRADE INTEGER NOT NULL,
  JOB_GRADE INTEGER NOT NULL,
+
  JOB_COUNTRY VARCHAR(15) NOT NULL,
  JOB_COUNTRY VARCHAR(15) NOT NULL,
+
  SALARY NUMERIC(10,2) NOT NULL,
  SALARY NUMERIC(10,2) NOT NULL,
+
  CONSTRAINT CT_EMPLOYEE_PK PRIMARY KEY (EMP_NO)
  CONSTRAINT CT_EMPLOYEE_PK PRIMARY KEY (EMP_NO)
+
);</syntaxhighlight>
);
 
</syntaxhighlight>
 
  
 
Algunos datos para almenos mostrar algo.... primero algunos clientes:
 
Algunos datos para almenos mostrar algo.... primero algunos clientes:
<syntaxhighlight lang="sql">
+
<syntaxhighlight lang="sql"> INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (1, 'Michael Design', 'San Diego', 'USA');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (1, 'Michael Design', 'San Diego', 'USA');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (2, 'VC Technologies', 'Dallas', 'USA');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (2, 'VC Technologies', 'Dallas', 'USA');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (3, 'Klämpfl, Van Canneyt and Co.', 'Boston', 'USA');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (3, 'Klämpfl, Van Canneyt and Co.', 'Boston', 'USA');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (4, 'Felipe Bank', 'Manchester', 'England');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (4, 'Felipe Bank', 'Manchester', 'England');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (5, 'Joost Systems, LTD.', 'Central Hong Kong', 'Hong Kong');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (5, 'Joost Systems, LTD.', 'Central Hong Kong', 'Hong Kong');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (6, 'Van der Voort Int.', 'Ottawa', 'Canada');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (6, 'Van der Voort Int.', 'Ottawa', 'Canada');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (7, 'Mrs. Mauvais', 'Pebble Beach', 'USA');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (7, 'Mrs. Mauvais', 'Pebble Beach', 'USA');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (8, 'Asinine Vacation Rentals', 'Lihue', 'USA');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (8, 'Asinine Vacation Rentals', 'Lihue', 'USA');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (9, 'Fax', 'Turtle Island', 'Fiji');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (9, 'Fax', 'Turtle Island', 'Fiji');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (10, 'FPC Corporation', 'Tokyo', 'Japan');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (10, 'FPC Corporation', 'Tokyo', 'Japan');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (11, 'Dynamic Intelligence Corp', 'Zurich', 'Switzerland');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (11, 'Dynamic Intelligence Corp', 'Zurich', 'Switzerland');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (12, '3D-Pad Corp.', 'Paris', 'France');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (12, '3D-Pad Corp.', 'Paris', 'France');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (13, 'Swen Export, Ltd.', 'Milan', 'Italy');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (13, 'Swen Export, Ltd.', 'Milan', 'Italy');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (14, 'Graeme Consulting', 'Brussels', 'Belgium');
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (14, 'Graeme Consulting', 'Brussels', 'Belgium');
+
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (15, 'Klenin Inc.', 'Den Haag', 'Netherlands');</syntaxhighlight>
INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (15, 'Klenin Inc.', 'Den Haag', 'Netherlands');
 
</syntaxhighlight>
 
  
 
Then some employees:
 
Then some employees:
<syntaxhighlight lang="sql">
+
<syntaxhighlight lang="sql"> INSERT INTO employee(emp_no, first_name, last_name, phone_ext, job_code, job_grade,  
INSERT INTO employee(emp_no, first_name, last_name, phone_ext, job_code, job_grade,  
 
 
   job_country, salary)
 
   job_country, salary)
 
   VALUES (1,'William','Shatner','1702','CEO',1,'USA',48000)
 
   VALUES (1,'William','Shatner','1702','CEO',1,'USA',48000)
INSERT INTO employee(emp_no, first_name, last_name, phone_ext, job_code, job_grade,  
+
INSERT INTO employee(emp_no, first_name, last_name, phone_ext, job_code, job_grade,  
 
   job_country, salary)
 
   job_country, salary)
 
   VALUES (2,'Ivan','Rzeszow','9802','Eng',2,'Russia',38000);
 
   VALUES (2,'Ivan','Rzeszow','9802','Eng',2,'Russia',38000);
INSERT INTO employee(emp_no, first_name, last_name, phone_ext, job_code, job_grade,  
+
INSERT INTO employee(emp_no, first_name, last_name, phone_ext, job_code, job_grade,  
 
   job_country, salary)
 
   job_country, salary)
   VALUES (3,'Erin','Powell','1703','Admin',2,'USA',45368);
+
   VALUES (3,'Erin','Powell','1703','Admin',2,'USA',45368);</syntaxhighlight>
</syntaxhighlight>
 
  
 
Por favor, crea la base de datos, la tabla e inserta los datos en el entorno de base de datos.
 
Por favor, crea la base de datos, la tabla e inserta los datos en el entorno de base de datos.
Line 129: Line 120:
 
Si estás utilizando SQLite, entonces puedes crear la mencionada base de datos en el directorio del proyecto ejecutanto sqlite:
 
Si estás utilizando SQLite, entonces puedes crear la mencionada base de datos en el directorio del proyecto ejecutanto sqlite:
  
<syntaxhighlight lang="bash">
+
<syntaxhighlight lang="bash"> sqlite employee.sqlite</syntaxhighlight>
sqlite employee.sqlite
 
</syntaxhighlight>
 
 
Ahora copia y pega lo siguientes sentencias CREATE TABLE e INSERT.
 
Ahora copia y pega lo siguientes sentencias CREATE TABLE e INSERT.
 
Para comprobar que los datos correctos se encuentran presentes entrar la siguiente consulta (query):
 
Para comprobar que los datos correctos se encuentran presentes entrar la siguiente consulta (query):
<syntaxhighlight lang="SQL">
+
<syntaxhighlight lang="SQL"> select * from customer;</syntaxhighlight>
select * from customer;
 
</syntaxhighlight>
 
 
Finaliza la sesión con:
 
Finaliza la sesión con:
<syntaxhighlight lang="SQL">
+
<syntaxhighlight lang="SQL"> .quit</syntaxhighlight>
.quit
 
</syntaxhighlight>
 
  
 
Con todo esto debería haber creado un fichero llamado employee.sqlite dentro del directorio del proyecto.
 
Con todo esto debería haber creado un fichero llamado employee.sqlite dentro del directorio del proyecto.
Line 149: Line 134:
 
* el directorio system (accesible a todas las aplicaciones).
 
* el directorio system (accesible a todas las aplicaciones).
  
Compile your project (even if it is empty) once to create the output directory, and (on Windows) copy the dll, as well as the employee.sqlite database, into that directory.
+
&nbsp;&nbsp;&nbsp;Compila el proyecto (incluso si está vacío) para crear el directorio de salida, y entonces (en Windows) copiar la dll y la BD en este directorio.
  
 
==== PostgreSQL ====
 
==== PostgreSQL ====
This section assumes you're using a Linux server and the shell; comparable steps can be done using Windows and GUI tools such as pgadmin.
 
 
Log in to your server and switch to the postgres account:
 
<syntaxhighlight lang=bash>
 
su - postgres -c psql # immediately start up psql SQL interpreter
 
</syntaxhighlight>
 
  
Create a user for the database and the tables:
+
Esta sección  asume que estás utilizando un servidor Linux y la shell; se pueden realizar pasos comparables utilizando Windows y utilidades gráficas tales como pgadmin o LazSplx.
<syntaxhighlight lang=SQL>
 
CREATE USER employee WITH PASSWORD 'hellopassword'; -- of course, adjust password to taste
 
-- something like  'CREATE ROLE' should appear indicating success.
 
-- to later change the password you can use something like
 
-- alter user employee with password '<newpasswordhere>';
 
  
-- We're going to let the password never expire; if you want more security, you can leave this step out:
+
Logeate en tu servidor y cambia a la cuenta del usuario postgres:
ALTER USER employee VALID UNTIL 'infinity'; --password never expires
 
  
-- Now we're tightening it up a bit again:
+
<syntaxhighlight lang=bash> su - postgres -c psql # inmediatamente comienza un intérprete de SQL llamado psql</syntaxhighlight>
-- Don't allow user to create a database or create other users:
 
ALTER USER employee NOCREATEDB NOCREATEUSER; --restrict object creation
 
-- something like 'ALTER ROLE' should appear indicating success.
 
  
-- Create our database:
+
Crea un usuario para la base de datos y sus tablas:
CREATE DATABASE employee;
 
-- something like CREATE DATABASE should appear indicating success.
 
  
-- Assign all privileges on database employee to user employee:
+
<syntaxhighlight lang=SQL> CREATE USER employee WITH PASSWORD 'hellopassword'; -- por supuesto, ajusta la contraseña a tu gusto
GRANT ALL PRIVILEGES ON DATABASE employee TO employee; -- allow user full permissions to database
+
-- something like  'CREATE ROLE' should appear indicating success.
-- something like GRANT should appear indicating success.
+
-- to later change the password you can use something like
 
+
-- alter user employee with password '<newpasswordhere>';
-- We create the table using a serial datatype - aka autonumber/autoincrement:
+
-- We're going to let the password never expire; if you want more security, you can leave this step out:
CREATE TABLE customer
+
ALTER USER employee VALID UNTIL 'infinity'; --password never expires
(
+
-- Now we're tightening it up a bit again:
 +
-- Don't allow user to create a database or create other users:
 +
ALTER USER employee NOCREATEDB NOCREATEUSER; --restrict object creation
 +
-- something like 'ALTER ROLE' should appear indicating success.
 +
-- Create our database:
 +
CREATE DATABASE employee;
 +
-- Debería aparecer algo similar a '''CREATE DATABASE''  a modo indicativo de resultado correcto.
 +
-- Asigna todos los privilegios en la base de datos employee al usuario employee:
 +
GRANT ALL PRIVILEGES ON DATABASE employee TO employee; -- asigna al usuario permisos totales a la base de datos.
 +
-- Debe aparecer algo similar a GRANT a modo indicativo de resultado correcto.
 +
-- We create the table using a serial datatype - aka autonumber/autoincrement:
 +
CREATE TABLE customer
 +
(
 
   cust_no serial NOT NULL,
 
   cust_no serial NOT NULL,
 
   customer character varying(25) NOT NULL,
 
   customer character varying(25) NOT NULL,
Line 190: Line 170:
 
   country character varying(15),
 
   country character varying(15),
 
   CONSTRAINT integ_60 PRIMARY KEY (cust_no )
 
   CONSTRAINT integ_60 PRIMARY KEY (cust_no )
);
+
);
  
-- Then create the employee table:
+
-- A continuación creamos la tabla employee:
CREATE TABLE EMPLOYEE
+
CREATE TABLE EMPLOYEE
(
+
(
 
   EMP_NO SERIAL NOT NULL,
 
   EMP_NO SERIAL NOT NULL,
 
   FIRST_NAME VARCHAR(15) NOT NULL,
 
   FIRST_NAME VARCHAR(15) NOT NULL,
Line 204: Line 184:
 
   SALARY NUMERIC(10,2) NOT NULL,
 
   SALARY NUMERIC(10,2) NOT NULL,
 
   CONSTRAINT CT_EMPLOYEE_PK PRIMARY KEY (EMP_NO)
 
   CONSTRAINT CT_EMPLOYEE_PK PRIMARY KEY (EMP_NO)
);
+
);
 +
 
 +
-- Now copy and paste the INSERT statements from the section above to insert the data.
  
-- Now copy and paste the INSERT statements from the section above to insert the data.
+
-- To test if the right data is present, enter this query:
 +
SELECT * FROM customer;
 +
-- You should see some customer data.
  
-- To test if the right data is present, enter this query:  
+
-- Exit out of psql:
SELECT * FROM customer;
+
\q </syntaxhighlight>
-- You should see some customer data.
 
  
-- Exit out of psql:
 
\q
 
</syntaxhighlight>
 
  
Now you should be on a shell logged in as the postgres user.
+
Ahora deberías encontrarte en una shell validado como usuario postgres.
  
If your server is on another machine than your development machine, make sure you allow network access to the database. See your postgresql documentation for details, but something like this should work:
+
Si tu servidor se encuentra en otra máquina distinta de su máquina de desarrollo, asegúrate de permitir acceso a la base de datos desde la red, no solo local.
<syntaxhighlight lang=bash>
+
Mira en la documentación de postgresql para más detallaes, pero por el momento algo similar a esto debería funcionar:
# please adjust nano (e.g. use vim,emacs,joe...) and the postgres version number depending on situation
 
nano /etc/postgresql/8.4/main/pg_hba.conf
 
</syntaxhighlight>
 
  
Verify if there is a line like - NOTE: replace 192.168.0.1 with your own LAN ip address range
+
<syntaxhighlight lang=bash> # please adjust nano (e.g. use vim,emacs,joe...) and the postgres version number depending on situation
 +
nano /etc/postgresql/8.4/main/pg_hba.conf
 +
</syntaxhighlight>
  
<nowiki>
+
Verifica que hay una línea como - NOTE: replace 192.168.0.1 with your own LAN ip address range
#allow access from local network using md5 hashed passwords:
 
  
host    all        all        192.168.0.1/24      md5
+
<nowiki> #allow access from local network using md5 hashed passwords:
</nowiki>
+
host    all        all        192.168.0.1/24      md5</nowiki>
  
or more restrictive:
+
O más restrictiva:
  
<nowiki>
+
<nowiki> # only allow network access to the employee database by the employee user
# only allow network access to the employee database by the employee user
+
host    employee        employee        192.168.0.1/24      md5</nowiki>
  
host    employee        employee        192.168.0.1/24      md5
+
Si no existe tal línea, añadela al final, salva y cierra tu editor.
</nowiki>
 
  
If there isn't such a line, add the line at the end, save and close your editor.
+
Ver la documentación de PostgreSQL para más detalles.
See PostgreSQL documentation for more details.
 
  
 
Reload PostgreSQL settings:
 
Reload PostgreSQL settings:
<syntaxhighlight lang=bash>  
+
<syntaxhighlight lang=bash> psql</syntaxhighlight>
psql
 
</syntaxhighlight>
 
 
then
 
then
<syntaxhighlight lang=SQL>  
+
<syntaxhighlight lang=SQL> SELECT pg_reload_conf(); --reload settings...
SELECT pg_reload_conf(); --reload settings...
+
-- ...and exit back to shell:
-- ...and exit back to shell:
+
\q</syntaxhighlight>
\q
 
</syntaxhighlight>
 
  
 
Test logging in to PostgreSQL.  
 
Test logging in to PostgreSQL.  
  
 
Note: by default PostgreSQL tries an ident/unix domain socket login which doesn't allow passwords. So we specify a host to force TCP/IP login:
 
Note: by default PostgreSQL tries an ident/unix domain socket login which doesn't allow passwords. So we specify a host to force TCP/IP login:
<syntaxhighlight lang=bash>
+
<syntaxhighlight lang=bash> psql -h 127.0.0.1 -d employee -U employee -W #Log in via tcp/ip. Enter your db password.</syntaxhighlight>
psql -h 127.0.0.1 -d employee -U employee -W #Log in via tcp/ip. Enter your db password.
 
</syntaxhighlight>
 
  
 
Make sure the required PostgreSQL dll/so and any required other libraries is installed - e.g. on Windows, they should be either:
 
Make sure the required PostgreSQL dll/so and any required other libraries is installed - e.g. on Windows, they should be either:
Line 267: Line 237:
 
Compile your project (even if it is empty) once to create the output directory, and (on Windows) copy the dllsinto that directory.
 
Compile your project (even if it is empty) once to create the output directory, and (on Windows) copy the dllsinto that directory.
 
[[Category:Databases/es]]
 
[[Category:Databases/es]]
[[category:Castellano|C]][[category:Español|C]]
+
[[category:Castellano|S]][[category:Español|S]]

Latest revision as of 13:28, 30 June 2022

Deutsch (de) English (en) español (es) français (fr) 日本語 (ja) 中文(中国大陆)‎ (zh_CN)

Introducción

Este tutorial muestra como programar con bases de datos (BBDD) utilizando un ejemplo práctico basado en el paquete SQLdb. Está primordialmente orientado a principiantes. Para quien esté buscando sobre fundamentos de bases de datos SQL debería leer libros y documentación relevante. Para este tutorial he utilizado Firebird con el fichero de bases de datos ejempo llamado employee.fdb. Se pueden utilizar otras bases de datos, para lo cual se requieren algunos ajustes que se mencionan en este texto.

Mientras que este tutorial puede parecer muy extenso, sin embargo es simplemente una explicación ajustada de lo que hay que teclear y porque. Como podrás deducir al final, la cantidad de código actual que se necesitará para tener una aplicación funcional no es tan grande. La mayor parte de los desarrolladores experimentados serán felizmente capaces de recorrer el código y entender de que trata.

Además, cuando finalices el capítulo te darás cuenta de que tienes en este ejemplo básico un programa que funciona.

Este tutorial está basado en [[SQLdb Tutorial1/de|el tutorial en alemán] realizado por el usuario Swen, pero su contenido ha sido extendido después del ejemplo básico. Swen necesita la versión en alemán como base. Si esto supone un problema entonces se puede renombrar esta versión y basar una nueva versión traducida.

De parte de Swen: gracias a Joost y Michael. sin su ayuda probablemente nunca se habría escrito este tutorial.

Requerimientos

Este tutorial se ha escrito para usarse con versiones recientes de Lazarus (Laz 1.0); debería también funcionar en versiones antiguas como Lazarus 0.9.30.

Además se necesita una base de datos relacional SQL, tal como Firebird (a ser posible una versión 2.0 o superior). Es sencillo si utilizas configuraciones estandar (e.g. por ejemplo el nombre de usuario SYSDBA y contraseña masterkey) y tienes instalada la base de datos employee.

Se puede utilizar cualquier otra base de datos (e.g. MySQL, PostgreSQL, Oracle, SQLite o de otro tipo utilizando ODBC): deberías tener la base de datos apropiada con su estructura de tablas (ver más abajo), y utilizar el correspondiente conector TSQLConnector (descendiente (también indicado abajo). Si tu base de datos tiene diferencias significativas en cuanto a transacciones etc., entonces haz una anotación en esta sección.

El tutorial ha sido actualizado con notas detalladas para SQLite y PostgreSQL.

Librerías de bases de datos Firebird en Windows

Finalmente, en Windows se va a necesitar tener presentes las librerías DLL de Firebird:

  • Deben estar en el directorio system (de esta forma estarían disponibles para todos los programas).
  • Además también pueden estar en el directorio de Lazarus (para tenerlo en tiempo de diseño en el IDE) y en el directorio de salida donde se obtiene el ejecutable (para arrancar el programa compilado).

Un modo fácil de obtener las librerías cliente es descargarse Firebird Embebido 2.5 desde [1] Extraer estos ficheros en el directorio de la aplicación:

 fbembed.dll
 firebird.msg
 ib_util.dll
 icudt30.dll
 icuin30.dll
 icuuc30.dll
 Microsoft.VC80.CRT.manifest
 msvcp80.dll
 msvcr80.dll

Renombrar fbembed.dll a fbclient.dll (el nombre regular para el cliente de Firebird cliente-servidor - esto ayuda a utilizarlo en versiones antiguas de Lazarus/FPC). La librería DLL embebida de Firebird puede actuar como un cliente regular de Firebird.

Asegúrate de que el fichero de la base de datos employee se encuentra en el directorio del proyecto. Se puede copiar desde el directorio examples/empbuild/ del servidor de Firebird 2.5.

Finalmente, compila el proyecto (aunque esté vacío) una vez para crear el directorio de salida, y copia las dlls, además del fichero de base de datos employee.fdb en el mismo directorio.

Librerias de base de datos Firebird en otros sistemas

En Linxu/OSX se necesitan también las librerías compartidas de cliente Firebird. En Linux se puede utilizar los médios de obtener programas, de la distribución (distro) en concreto de las muchas existentes, para obtener los paquetes de cliente de Firebird, e.g, en la distro debian sería así:

 aptitude install libfbclient2 firebird-dev #necesitamos la versión de desarrollo (dev) porque FPC 2.6 y anteriores bucan el fichero libfbclient.so

No Firebird or employee.fdb installed?

If you don't have the employee sample database installed or are using a different database, here is a minimal version of the table we'll be using (note: directions for some specific databases can be found below).

Creamos una tabla llamada EMPLOYEE que será utilizada en un tutorial posterior.

 CREATE TABLE CUSTOMER
 (
   CUST_NO INTEGER NOT NULL,
   CUSTOMER VARCHAR(25) NOT NULL,
   CITY VARCHAR(25),
   COUNTRY VARCHAR(15),
   CONSTRAINT CT_CUSTOMER_PK PRIMARY KEY (CUST_NO)
 );
 CREATE TABLE EMPLOYEE
 (
   EMP_NO INTEGER NOT NULL,
   FIRST_NAME VARCHAR(15) NOT NULL,
   LAST_NAME VARCHAR(20) NOT NULL,
   PHONE_EXT VARCHAR(4),
   JOB_CODE VARCHAR(5) NOT NULL,
   JOB_GRADE INTEGER NOT NULL,
   JOB_COUNTRY VARCHAR(15) NOT NULL,
   SALARY NUMERIC(10,2) NOT NULL,
   CONSTRAINT CT_EMPLOYEE_PK PRIMARY KEY (EMP_NO)
 );

Algunos datos para almenos mostrar algo.... primero algunos clientes:

 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (1, 'Michael Design', 'San Diego', 'USA');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (2, 'VC Technologies', 'Dallas', 'USA');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (3, 'Klämpfl, Van Canneyt and Co.', 'Boston', 'USA');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (4, 'Felipe Bank', 'Manchester', 'England');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (5, 'Joost Systems, LTD.', 'Central Hong Kong', 'Hong Kong');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (6, 'Van der Voort Int.', 'Ottawa', 'Canada');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (7, 'Mrs. Mauvais', 'Pebble Beach', 'USA');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (8, 'Asinine Vacation Rentals', 'Lihue', 'USA');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (9, 'Fax', 'Turtle Island', 'Fiji');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (10, 'FPC Corporation', 'Tokyo', 'Japan');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (11, 'Dynamic Intelligence Corp', 'Zurich', 'Switzerland');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (12, '3D-Pad Corp.', 'Paris', 'France');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (13, 'Swen Export, Ltd.', 'Milan', 'Italy');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (14, 'Graeme Consulting', 'Brussels', 'Belgium');
 INSERT INTO CUSTOMER (CUST_NO, CUSTOMER, CITY, COUNTRY) VALUES (15, 'Klenin Inc.', 'Den Haag', 'Netherlands');

Then some employees:

 INSERT INTO employee(emp_no, first_name, last_name, phone_ext, job_code, job_grade, 
  job_country, salary)
  VALUES (1,'William','Shatner','1702','CEO',1,'USA',48000)
 INSERT INTO employee(emp_no, first_name, last_name, phone_ext, job_code, job_grade, 
  job_country, salary)
  VALUES (2,'Ivan','Rzeszow','9802','Eng',2,'Russia',38000);
 INSERT INTO employee(emp_no, first_name, last_name, phone_ext, job_code, job_grade, 
  job_country, salary)
  VALUES (3,'Erin','Powell','1703','Admin',2,'USA',45368);

Por favor, crea la base de datos, la tabla e inserta los datos en el entorno de base de datos.

SQLite

Si estás utilizando SQLite, entonces puedes crear la mencionada base de datos en el directorio del proyecto ejecutanto sqlite:

 sqlite employee.sqlite

Ahora copia y pega lo siguientes sentencias CREATE TABLE e INSERT. Para comprobar que los datos correctos se encuentran presentes entrar la siguiente consulta (query):

 select * from customer;

Finaliza la sesión con:

 .quit

Con todo esto debería haber creado un fichero llamado employee.sqlite dentro del directorio del proyecto.

Hay que asegurarse de tener instaladas las librerías cliente de sqlite dll/so - e.g. en windows la librería sqlite3.dll debería ubicarse en:

  • el directorio de salida de proyecto de Lazarus.
  • el directorio system (accesible a todas las aplicaciones).

   Compila el proyecto (incluso si está vacío) para crear el directorio de salida, y entonces (en Windows) copiar la dll y la BD en este directorio.

PostgreSQL

Esta sección asume que estás utilizando un servidor Linux y la shell; se pueden realizar pasos comparables utilizando Windows y utilidades gráficas tales como pgadmin o LazSplx.

Logeate en tu servidor y cambia a la cuenta del usuario postgres:

 su - postgres -c psql # inmediatamente comienza un intérprete de SQL llamado psql

Crea un usuario para la base de datos y sus tablas:

 CREATE USER employee WITH PASSWORD 'hellopassword'; -- por supuesto, ajusta la contraseña a tu gusto
 -- something like  'CREATE ROLE' should appear indicating success.
 -- to later change the password you can use something like
 -- alter user employee with password '<newpasswordhere>';
 -- We're going to let the password never expire; if you want more security, you can leave this step out:
 ALTER USER employee VALID UNTIL 'infinity'; --password never expires
 -- Now we're tightening it up a bit again:
 -- Don't allow user to create a database or create other users:
 ALTER USER employee NOCREATEDB NOCREATEUSER; --restrict object creation
 -- something like 'ALTER ROLE' should appear indicating success.
 -- Create our database:
 CREATE DATABASE employee;
 -- Debería aparecer algo similar a '''CREATE DATABASE''  a modo indicativo de resultado correcto.
 -- Asigna todos los privilegios en la base de datos employee al usuario employee:
 GRANT ALL PRIVILEGES ON DATABASE employee TO employee; -- asigna al usuario permisos totales a la base de datos.
 -- Debe aparecer algo similar a GRANT a modo indicativo de resultado correcto.
 -- We create the table using a serial datatype - aka autonumber/autoincrement:
 CREATE TABLE customer
 (
  cust_no serial NOT NULL,
  customer character varying(25) NOT NULL,
  city character varying(25),
  country character varying(15),
  CONSTRAINT integ_60 PRIMARY KEY (cust_no )
 );

 -- A continuación creamos la tabla employee:
 CREATE TABLE EMPLOYEE
 (
  EMP_NO SERIAL NOT NULL,
  FIRST_NAME VARCHAR(15) NOT NULL,
  LAST_NAME VARCHAR(20) NOT NULL,
  PHONE_EXT VARCHAR(4),
  JOB_CODE VARCHAR(5) NOT NULL,
  JOB_GRADE INTEGER NOT NULL,
  JOB_COUNTRY VARCHAR(15) NOT NULL,
  SALARY NUMERIC(10,2) NOT NULL,
  CONSTRAINT CT_EMPLOYEE_PK PRIMARY KEY (EMP_NO)
 );

 -- Now copy and paste the INSERT statements from the section above to insert the data.

 -- To test if the right data is present, enter this query: 
 SELECT * FROM customer;
 -- You should see some customer data.

 -- Exit out of psql:
 \q


Ahora deberías encontrarte en una shell validado como usuario postgres.

Si tu servidor se encuentra en otra máquina distinta de su máquina de desarrollo, asegúrate de permitir acceso a la base de datos desde la red, no solo local. Mira en la documentación de postgresql para más detallaes, pero por el momento algo similar a esto debería funcionar:

 # please adjust nano (e.g. use vim,emacs,joe...) and the postgres version number depending on situation
 nano /etc/postgresql/8.4/main/pg_hba.conf

Verifica que hay una línea como - NOTE: replace 192.168.0.1 with your own LAN ip address range

#allow access from local network using md5 hashed passwords: host all all 192.168.0.1/24 md5

O más restrictiva:

# only allow network access to the employee database by the employee user host employee employee 192.168.0.1/24 md5

Si no existe tal línea, añadela al final, salva y cierra tu editor.

Ver la documentación de PostgreSQL para más detalles.

Reload PostgreSQL settings:

 psql

then

 SELECT pg_reload_conf(); --reload settings...
 -- ...and exit back to shell:
 \q

Test logging in to PostgreSQL.

Note: by default PostgreSQL tries an ident/unix domain socket login which doesn't allow passwords. So we specify a host to force TCP/IP login:

 psql -h 127.0.0.1 -d employee -U employee -W #Log in via tcp/ip. Enter your db password.

Make sure the required PostgreSQL dll/so and any required other libraries is installed - e.g. on Windows, they should be either:

  • in your Lazarus + project output directory or
  • in your system directory

Compile your project (even if it is empty) once to create the output directory, and (on Windows) copy the dllsinto that directory.