SQLite/es

From Lazarus wiki
Jump to navigationJump to search

English (en) español (es) français (fr) 日本語 (ja) polski (pl) русский (ru) 中文(中国大陆)‎ (zh_CN)

Soporte para SQLite en FPC/Lazarus

SQLite es una base de datos embebida (sin servidor) de simple usuario que puede ser utilizada en aplicaciones FPC y Lazarus. Se pueden utilizar varios drivers para el acceso a SQLite desde programas FPC/Lazarus.

Es necesario que dichos drivers de SQLite (librerias/dll) se ubiquen en el directorio de proyecto y en del ejecutable resultante (y distribuirlos con el ejecutable) para que funcione.

Built-in SQLDB

FPC/Lazarus incluyen componentes SQLDB que aportan soporte para bases de datos SQLitet (TSQLite3Connection), permitiendo por ejemplo crear interfaces gráficos (GUIS) con componentes tales como dbgrids. La ventaja de utilizar SQLDB es que resulta bastante fácil el cambio a otra base de datos diferente como puede ser Firebird o PostgreSQL sin tener por ello que realizar grandes cambios.

Ver debajo para más detalles.

Spatialite support

Spatialite son extensiones GIS para SQLite que se pueden utilizar dentro de SQLDB. Ver Spatialite.

Support for SQLite encryption

En versiones recientes de FPC (implementadas en Marzo de 2012), SQLDB incluye soporte para algunas versiones extendidas de SQLite3 que encriptan la base de datos SQLite mediante el algoritmo AES. Para habilitar la llave (key) de encriptación se tiene disponible la propiedad "password".

Ejemplos:

- SQLCipher: código abierto (open source), e.g. Windows binaries not for free (tienes que compilarlos por ti mismo).

- System.Data.SQLite: código abierto (open source), binarios disponibles para Windows (32, 64, CE), descarga e.g uno de los binarios precompilados y renombra SQLite.Interop.dll como sqlite3.dll (si estás utilizando los enlazados estáticamente, presumiblemente necesitas renombrar System.Data.SQLite.DLL como sqlite3.dll)

- wxSQLite3: open source, disponibles algunos binarios para Linux (ex: https://launchpad.net/ubuntu/oneiric/+package/libwxsqlite3-2.8-0)

Zeos

Zeos

SQLitePass

SqlitePass components. Estado: desconocido.

TSQLite3Dataset y TSQLiteDataset

Existen paquetes diferenciados tales como TSQLiteDataset y TSQLite3Datases; leer más abajo para una descripción sobre como utilizarlos. Para encontrar la API de referencia y más tutoriales puedes visitar la dirección sqlite4fpc homepage.

TSqliteDataset y TSqlite3Dataset son descendientes de TDataset que acceden, respectivamente a bases de datos SQLite2.8.x y 3.x.x. Para nuevos proyectos debería utilizarse presumiblemente TSQlite3Dataset como SQLite 3.x (es la versión actual).

A continuación se muestra un listado de las principales ventajas y desventajas en comparación con otros drivers/métodos de acceso de FPC/Lazarus.

Ventajas:

  • Flexible: los programadores pueden escoger entre utilizar o no el lenguaje SQL, permitiendo trabajar con capas de tablas simples o con capas complejas que permite SQL/SQLite.

Desventajas:

  • El cambio hacia otras bases de datos es más difícil que si se utilizan componentes SQLDB o Zeos.
Note-icon.png

Nota: Dicho esto, bastantes programadores utilizarán SQLDB o Zeos dadas las ventajas que aportan a menos que necesiten un menor nivel de acceso a la librería SQLite

Utilizando componentes SQLdb con SQLite

Estas instrucciones se centran en SQLDB (la TSQLite3Connection) específicamente para SQLite. Para una vista general, echa un vistazo a SqlDBHowto la cual tiene bastante información útil sobre componentes SQLdb.

Para un tutorial sobre como crear un programa de base de datos con interface gráfica de usuario (GUI) escrita para SQLite/SQLDB (así como para Firebird/SQLDB, PostgreSQL/SQLDB, básicamente soporta cualquier RDBMS SQLDB)se puede visitar SQLdb_Tutorial1.

Utilizaremos una combinación de tres componentes de la solapa SQLdb de Lazarus: TSQLite3Connection, TSQLTransaction y TSQLQuery. TSQLQuery actúa como nuestro TDataset; en el caso más simple representa una de nuestras tablas. En pos de la simplicidad: asegúrate de tener previamente una base de datos SQLite y que no tienes que crear una nueva en ese instante.

TSQLite3Connection se puede encontrar en la unit sqlite3conn, si necesitas declararla por ti mismo o si estás trabajando en FreePascal.

Los tres componentes están conectados entre ellos como es habitual: en TSQLQuery hay que establecer las propiedades Database y Transaction, en TSQLTransaction la propiedad Database.No hay mucho más que hacer en los componentes Transaction y Connection, la mayor parte de las cosas interesantes se realizarán en el componente TSQLQuery.

A continuación se explica como configurar los componentes:

TSQLite3Connection:

  • DatabaseName: establecer esta propiedad con el nombre del fichero SQLite (¡trayecto absoluto!). Desafortunadamente, no se puede simplemente utilizar un trayecto relativo que trabaje sin cambios tanto en tiempo de ejecución como de diseño ***¿es esto todavía cierto? Can't you just copy the db file in a post-build shell script or symlink it?***. You should make sure that at application start the correct path to the file is always set programmatically, no matter what it contained at designtime.

Nota: para establecer el trayecto completo a la librería (si ubicas tu sqlite dll/so/dylib en un lugar donde el sistema operativo no lo encuentra por defecto, tal como el directorio application en Linux/OSX), puedes establecer la propiedad SQLiteLibraryName (ANTES de que sea establecida una conexión e.g. en el evento OnCreate del formulario principal), tal como esto:

SQLiteLibraryName:='./sqlite3.so';

TSQLQuery:

  • SQL: Set it to some simple select query on one of your tables. Por ejemplo, si tienes una tabla llamada 'foo' y necesitas que este dataset represente a dicha table entonces utiliza lo siguiente:
    SELECT * FROM foo
    
  • Active: establécelo a True desde el IDE para testear si todo está configurado correctamente. Esto además activará automáticamente los objetos transaction y connection. Si recibes un mensaje de error entonces o bien DatabaseName de la conexión no es correcta o la query de SQL está mal. Posteriormente, cuando añadimos los campos (ver más abajo) los establecemos de nuevo como inactivos. No queremos que el IDE bloquee la base de datos SQLite cuando testeamos la aplicación (recuerda: ¡monousuario!).
  • Probably not necessary for proper operation - will need to be checked (June 2012) Now we can add Fields to our TSQLQuery. While the components are still set to active do a right click and "edit fields...". Click the "+" button and add fields. It will list all fields your SQL query returned. Add every field you will need, you can also add lookup fields here; in this case just make sure you have already defined all needed fields in the other datasets before you start adding lookup fields that refer to them. If your table has many columns and you don't need them all you can just leave them out, you can also make your SQL a bit more specific.
  • In your code you need to call SQLQuery.ApplyUpdates and SQLTransaction.Commit, TSQLQuery.AfterPost and AfterInsert events are a good place for this when using it with data aware controls but of course you can also postpone these calls to a later time. If you don't call them, the database will not be updated.
  • "Database is locked": The IDE might still be locking the database (SQLite is a single user database), you probably forgot to set the components to inactive and disconnected again after you were done defining all the fields of your TSQLQuery objects. Use the Form's OnCreate event to set the path and activate the objects at runtime only. Most of the things you set in the TSQLQuery from within the IDE don't require (and some don't even allow) them to be active at design time, the only exception is defining the fields where it wants to read the table design, so inactive at design time should be the normal state.
  • Your tables should all have a primary key and you must make sure that the corresponding field has pfInKey and nothing else in its PoviderFlags (these flags control how and where the field is used when automatically constructing the update and delete queries).
  • If you are using lookup fields
    • make sure the ProviderFlags for the lookup field is completely empty so it won't attempt to use its name in an update query. The lookup field itself is not a data field, it only acts on the value of another field, the corresponding key field, and only this key field will later be used in the update queries. You can set the key field to hidden because usually you don't want to see it in your DBGrid but it needs to be defined.
    • LookupCache must be set to True. At the time of this writing for some reason the lookup field will not display anything otherwise (but still work) and strangely the exact opposite is the case when working with the TSQLite3Dataset or other TXXXDataset components, here it must be set to False. I'm not yet sure whether this is intended behavior or a bug.

After the above is all set up correctly, you should now be able to use the TSQLQuery like any other TDataset, either by manipulating its data programmatically or by placing a TDatasouce on the Form, connecting it to the TSQLQuery and then using data contols like TDBGrid etc.

Tips

  • Utiliza el procedimiento TSQLite3Connection.CreateDB para crear una nueva base de datos SQLite.

Utilizando TSQLite3Dataset

Esta sección detalla como utilizar los componentes TSQLite3Dataset y TSQLite3Dataset para acceder a bases de datos SQlite. por Luiz Américo luizmed(at)oi(dot)com(dot)br


Requerimientos

  • Para bases de datos sqlite2 (legado):
    • FPC 2.0.0 or higher
    • Lazarus 0.9.10 o superior.
    • SQLite runtime library 2.8.15 or above*
  • Sqlite2 ya no está en fase de mantenimiento y el fichero binario ya no se encuentra en el sitio de sqlite.
  • Para basesd e datos sqlite3:
    • FPC 2.0.2 o superior.
    • Lazarus 0.9.11 (svn revisión 8443) o superior.
    • sqlite runtime library 3.2.1 or higer (get it from www.sqlite.org)

Before initiating a lazarus project, ensure that:

  • the sqlite library is either
    • in the system PATH or
    • in the executable output directory and Lazarus (or current project) directories - this option might work on Windows only
  • under Linux, put cmem as the first unit in uses clause of the main program
    • In Debian, Ubuntu and other Debian-like distros, in order to build Lazarus IDE you must install the packages libsqlite-dev/libsqlite3-dev, not only sqlite/sqlite3 (Also applies to OpenSuSe)

Como utilizar (utilización básica)

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

En tiempo de diseño, establecer las siguientes propiedades:

  • FileName: path of the sqlite file [required]
  • TableName: name of the table used in the sql statement [required]
  • SQL: a SQL select statement [optional]
  • SaveOnClose: The default value is false, which means that changes are not saved. One can change it to true. [optional]
  • Active: Needs to be set at design time or at program startup. [required]

Creating a Table (Dataset)

Double-click 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 shown.

Estos son todos los tipos soportados por TSqliteDataset y TSqlite3Dataset:

  • Integer
  • AutoInc
  • String
  • Memo
  • Bool
  • Float
  • Word
  • DateTime
  • Date
  • Time
  • LargeInt
  • Currency

Retrieving the data

Después de crear la tabla o con una tabla creada previamente, abrir el dataset con el método Open.

Si la propiedad SQL no se ha establecido a un valor entonces se recogen todos los registros de todos los campos, lo mismo que si se establece SQL a:

SQL := 'Select * from TABLENAME';

Applying changes to the underlying datafile

To use the ApplyUpdates function, the dataset must contain at least one field that fulfills 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, just call

ApplyUpdates;
Light bulb  Nota: If both conditions are set, the field corresponding to PrimaryKey is used to apply the updates.
Light bulb  Nota: 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.
Master/detail example

An example of implementing master/detail (customer/orders) using locate can be found here: TSqlite3 Master Detail Example. Implementing master/detail with locate can also be done in SQLDB and probably Zeos.

Remarks

  • Although it has been tested with 10,000 records and worked fine, TSqliteDataset keeps all the data in memory, so remember to retrieve only the necessary data (especially 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 sqlite 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/src/sqlite SVN directory

See also