Difference between revisions of "Databases in Lazarus/es"

From Free Pascal wiki
Jump to navigationJump to search
Line 66: Line 66:
 
*Calling the database post method saves the values (edit) or record (insert).  In some dataset descendants, they will be written to the database immediately, while in others they will be stored in a list of updates until a further call is made to save all changes to the database.  Finally, even when they are written to the database, you may still have to call a "commit" method to make the database write them permanently.  All of this also varies considerably with the dataset descendant, so look up the details for the one you are using.
 
*Calling the database post method saves the values (edit) or record (insert).  In some dataset descendants, they will be written to the database immediately, while in others they will be stored in a list of updates until a further call is made to save all changes to the database.  Finally, even when they are written to the database, you may still have to call a "commit" method to make the database write them permanently.  All of this also varies considerably with the dataset descendant, so look up the details for the one you are using.
  
==Data Controls==
+
==Componentes de Datos==
  
 
To use any of these controls, add the control to a form and set at least the datasource property.  Other key properties will be noted.
 
To use any of these controls, add the control to a form and set at least the datasource property.  Other key properties will be noted.

Revision as of 19:21, 26 June 2008

Objetivo

   Esta página pretende ofrecer un panorama general de la utilización de bases de datos en Lazaraus, y para proporcionar un punto en el que relacionar otras páginas sobre bases de datos.

Conjunto de Datos (Datasets)

   La utilización de Bases de Datos en Lazarus (o FreePascal) está fundamentada principalmente en la clase TDataset, que representa una tabla o consulta en la aplicación. Como con muchas otras clases fundamentales, no se usará la misma de forma directa, sino que se hará mediante una clase derivada. Esto tiene su porqué: pra ofrecer acceso a distintas clase de Bases d Datos, como archivos de dBase o texto locales, o bases de datos remotas como PostgreSQL, Firebird, MySQl y muchas otras. Algunos de las clase derivadas de TDataset acceden a las tablas de las bases de datos directamente, mientras otras utilizan componentes adicionales o librerías para llevar a cabo el acceso.

   Ver las clases derivadas de acceso a datos en esta página.

   Las clases derivadas de TDataset, que no son componentes visuales son (habitualmente) parte del Librería de Componentes Libres -Free Component Library (FCL)- en lugar de formar parte de la librería de Componentes de Lazarus -Lazarus Component Library (LCL)-.

Utilizando Datasets

   Los components Datasets se pueden utilizar indistintamente por código o cómo componentes visuales. En una aplicación Lazarus normal se suelen utilizar ambos métodos. En cualquier caso, el primer paso es crear el descendiente de TDataSet, iniciarlo para conectarlo con la tabla o consulta, por último realizar la conexión, abriendo el conjunto de datos. Esto se puede hacer por código en tiempo de ejecución o colocando el componente en el formulario y dando valores a las propiedades durante el diseño. Los detalles concretos varían bastante según las diferentes clases derivadas de TDataset, por ello hay que ver las distintas guías para los componentes de acceso a distintas Bases de Datos.

   Cuando se abre el conjunto de datos (Dataset) se crean una serie de componentes de campos, uno por cada campo o columna de la tabla o consulta que se ha abierto. Cada componente de campo es descendiente de TField, adecuado al tipo particular del campo, v.gr., TStringField, para campos de tipo alfabético.

Utilizando datasets desde código

El acceso mediante código está explicado con más detalle en Utilizando componentes Dataset y de campo, esta es una visión general muy simple:

  • Usar el derivado de TDataset para abrir la tabla o consulta, filtrar para ver las filas deseadas y moverse de una fila a otra.
  • Usar un componente derivado de TField para:
    • Acceder a la información general sobre los campos
    • Acceder a los valores concretos para la fila actual. (mediante las propiedades As..., como AsString, AsInteger, etc.)
  • Acceder a los campos de un componente derivado de TDataset de esta forma:
    • La propiedad Fields (Campos), v.gr. Fields[0] es el primer campo,
    • Con el método FieldByName, v.gr. FieldByName('EDAD') devuelve el contenido del campo asociado con el campo de la Base de datos de nombre 'EDAD'.

Utilizando componentes visuales enlazados a datos (data-aware components)

   Para utilizar bases de datos en una aplicación Lazarus al estilo RAD, normalmente se configura el componente de datos Dataset en el momento del diseño y se usan componentes enlazados a datos, de la forma siguiente

  • Añadir el componente de datos deseado, junto con los componentes adicionales si son necesarios, en el formulario, y abrirlo, poniendo el valor la propiedad Active a verdadera.
  • Añadir un componente TDatasource (de la pestaña Data Access) al formulario, y enlazarlo con el componente dataset, dando como valor de su propiedad Dataset el nombre dado a este.
  • Situar los componentes ligados a datos desde la pestaña Data Controls en el formulario y enlazarlos con el componente DataSource (no con el dataset)
  • La mayoría de los controles enlazan un único campo, por lo que es necesario, seleccionar el que deseamos mostrar.

   Ver Componentes de datos más adelante para más detalllas de los componentes.

Dataset State

Datasets can be in a number of states. While there are quite a few (look up TDataSetState in the source), the main ones to be aware of initally are

State Function
dsInactive The dataset is closed
dsBrowse The user can browse through the dataset, looking at values
dsEdit The user can edit values on the current row. Values are not saved until a post is performed.
dsInsert A new row has been added, and the user can set the values. The record is not saved until a post is performed

The other states are fairly transitory, and are usually handled "automatically". They are used internally and in more complicated code. If your database only views data, and you open the dataset at design time, you can largely ignore the state, as it will mostly be dsBrowse. However, most applications will want to change the data at some stage. If you are using data-aware controls, they will handle a lot of this automatically. If you change the text in a DBEdit control, for example, it will put the dataset into dsEdit state - unless you are already in dsEdit or dsInsert. If you "scroll" to a different record while the current state is dsEdit or dsInsert, that record will be "posted" and the dataset revert to dsBrowse. However, if you are accessing the dataset from code, you will often have to change the state in code as well. The dbNavigator control (see below) allows the user to change the state explicitly.

Post and Cancel

If you have edited or inserted a record, the new values are held in a buffer.

  • Calling the dataset cancel method removes the new record (insert) or reverts the values to their previous values (edit).
  • Calling the database post method saves the values (edit) or record (insert). In some dataset descendants, they will be written to the database immediately, while in others they will be stored in a list of updates until a further call is made to save all changes to the database. Finally, even when they are written to the database, you may still have to call a "commit" method to make the database write them permanently. All of this also varies considerably with the dataset descendant, so look up the details for the one you are using.

Componentes de Datos

To use any of these controls, add the control to a form and set at least the datasource property. Other key properties will be noted.

Single Field Controls

These controls all attach to a single field. As well as datasource, set the field name. Controls include:

DBGrid control

This control can show a number of fields in a row/column layout - in fact by default it shows them all. However, you can put entries into the columns collection to restrict it to specific fields and to set the widths and titles of each column.

There seem to be some issues currently with editing in dbGrid, so while editing is certainly possible, it may be safer to use it as display only (set readonly to true) and provide single field controls for editing.

Navigator Control

This control gives the user some direct control over the dataset. It allows the user to:

  • Move to the next or previous record, or to the start or end of the records
  • Add a new record (equivalent to a dataset.insert method call)
  • Put the dataset into edit mode
  • Delete a record
  • Post or Cancel current changes
  • Refresh the data (useful in multiuser database applications)

Key Properties:

  • VisibleButtons: Lets you control what the user can do. For example, if deletes are not allowed, hide the delete button. If you have a DBGrid attached to the same dataset, you may decide you do not need the next and prior buttons.
  • Width: If you do not show all buttons, you may want to set the width to (height*number_of_visible_buttons)