Lazarus Tdbf Tutorial/es

From Lazarus wiki
Revision as of 07:06, 22 November 2005 by Mgsalvador (talk | contribs)
Jump to navigationJump to search

Deutsch (de) English (en) español (es) français (fr) português (pt) русский (ru) 中文(中国大陆)‎ (zh_CN)

(Traduciendo.../On Translation...)

Resumen

Este tutorial trata sobre el desarrollo elemental de bases de datos usando el componente TDbf (de Micha Nelissen) con Lazarus. Hay disponible documentación adicional para TDbf. Esta página fue creada por Tony Maro, pero ¡se agradecen otras colaboraciones!

Lo que necesitará

Sin duda pronto será más fácil cuando FreePascal libere la próxima versión 2.0, sin embargo, actualmente necesitará una versión reciente de CVS de FPC 1.9.X para usar adecuadamente el componente TDbf. Se puede descargar solo el componente TDbf y usarlo con la versión 1.1 de FreePascal, sin embargo, este documento fue escrito pensando en la 1.9.X, en parte debido a correcciones en otros componentes de bases de datos usados en Lazarus.

También necesitará instalar el paquete DbfLaz que trae Lazarus. Está situado en la carpeta lazarus/components/tdbf/.

¿Qué se puede hacer con TDbf?

El componente TDbf proporciona a Lazarus (y otros entornos) acceso a tablas dBase y FoxPro. Permite la lectura, la escritura y la creación de tablas dBase III+, dBase IV, dBase visual VII y FoxPro. Hace todo esto sin la necesidad de bibliotecas o de gestores de bases de datos adicionales. Simplemente ponga el componente TDbf en su formulario y tendrá acceso inmediato a un entorno de bases de datos de plataforma-cruzada. TDbf funciona tanto en Windows como en Linux usando Lazarus.

Cómo crear una nueva tabla

Como no hay todavía una aplicación "Database Desktop" para Lazarus, debemos crear una nueva base de datos mediante código.

Establecer la ruta de acceso

Es recomendable crear una carpeta para sus aplicaciones de bases de datos. Esto simplifica la realización de copias de seguridad de los datos. Hay dos maneras de establecer la ruta de acceso. Puede fijar la ruta completa usando la propiedad FilePathFull, o puede establecer una ruta relativa a la ruta del programa con FilePath. Por ejemplo, estableciendo "FilePath" en tiempo de ejecución a "datos/" utilizaría una subcarpeta de datos dentro de la carpeta del archivo ejecutable. Fijar la propiedad "FilePathFull" a "/var/datos/" colocaría todo en esa carpeta, no teniendo en cuenta la ubicación del programa.

Eligir un TableLevel

Por omisión, TDbf creará tablas dBase IV. Aunque son muy compatibles, hay características que puede desear usar que no están disponibles. Para poder utilizar campos auto-incrementables, debe usar algo más nuevo. Los tipos de tabla posibles son:

  • 3 dBase III+
  • 4 dBase IV
  • 7 Visual dBase VII
  • 25 FoxPro

Para elegir un tipo de tabla seleccione apropiadamente la propiedad TableLevel.

Añadir campos

La creación de campos para su nueva tabla en tiempo de ejecución se realiza como en Delphi. Una vez establecidas las propiedades FilePath, TableLevel, y TableName, hay que utilizar la propiedad FieldDefs para determinar su estructura. Por ejemplo:

MyDbf.FilePathFull := '/ubicacion/para/mis/datos';
MyDbf.TableLevel := 7;
MyDbf.TableName := 'clientes.dbf'; // nota: ¿es realmente necesario .dbf?
With MyDbf.FieldDefs do begin
  Add('Id', ftAutoInc, 0, True);
  Add('Name', ftString, 80, True);
End;

Los tipos de campo definidos son:

  • ftUnknown
  • ftString
  • ftSmallInt
  • ftInteger
  • ftWord
  • ftBoolean
  • ftFloat
  • ftCurrency (TableLevel 25)
  • ftBCD (TableLevel 25)
  • ftDate
  • ftTime
  • ftDateTime
  • ftBytes (TableLevel 25)
  • ftVarBytes
  • ftAutoInc (TableLevel 7 or 25)
  • ftBlob
  • ftMemo
  • ftGraphic
  • ftFmtMemo
  • ftParadoxOle
  • ftDBaseOle
  • ftTypedBinary
  • ftCursor
  • ftFixedChar
  • ftWideString
  • ftLargeInt
  • ftADT
  • ftArray
  • ftReference
  • ftDataSet
  • ftOraBlob
  • ftOraClob
  • ftVariant
  • ftInterface
  • ftIDispatch
  • ftGuid
  • ftTimeStamp
  • ftFMTBcd

Los tipos que aparecen en negrita son los soportados en la actualidad.

¡Siga adelante y créela!

Una vez que ha definido los campos deseará usarlos en su nueva tabla, puede seguir adelante y crearla con:

   MyDbf.CreateTable;

Añadir índices a una tabla

Si su base de datos es bastante grande, deberá definir índices para hacer búsquedas más rápidas. Para cambiar la estructura de índices de una tabla, deberemos tener acceso exclusivo a la tabla -mientras la creamos.

       MyDbf.Exclusive := True;
       MyDbf.Open;

Justo ahora, tenemos que añadir el índice.

       MyDbf.AddIndex('custid', 'Id', [ixPrimary, ixUnique]);
       MyDbf.AddIndex('custname','Name', [ixCaseInsensitive]);
       MyDbf.Close;

Únalo todo y lo conseguirá...

El siguiente ejemplo crea una tabla "clientes" mediante código. Esto, por supuesto, sólo necesita hacerlo una vez y justo después de ABRIR la tabla, no la cree ;-)

{ Necesitamos que las siguientes unidades aparezcan en la clásula USES:}
{ uses 
       Dbf, db, Dbf_Common                                   }
{ Dbf lo hará, automáticamente,cuando pongamos el componente TDbf en el formulario...   }
{ pero necesitaremos db para el objeto DataSet y Dbf_Common }
{ para cosas como las definiciones de tipos de campo        }
var
  MyDbf: TDbf;
begin
  MyDbf := TDbf.Create(nil);
  try
    { usar ruta relativa para la carpeta "datos" }
    MyDbf.FilePath := 'data/'; 
    { queremos utilizar tablas Visual dBase VII }
    MyDbf.TableLevel := 7;
    MyDbf.Exclusive := True;
    MyDbf.TableName := 'customers.dbf';
    With MyDbf.FieldDefs do begin
      Add('Id', ftAutoInc, 0, True);
      Add('Name', ftString, 80, True);
    End;
    MyDbf.CreateTable;
    MyDbf.Open;
    MyDbf.AddIndex('custid', 'Id', [ixPrimary, ixUnique]);
    { add a secondary index }
    MyDbf.AddIndex('custname','Name', [ixCaseInsensitive]);
    MyDbf.Close;
  finally
    MyDbf.Free;
  end;
end;

Archivos índice externos

The TDbf also supports storing secondary indexes in a separate file. This might be helpful if the database is expected to be very large. Secondary index files are created almost identically to normal indexes, but with the addition of the '.ndx' file extension:

    MyDbf.AddIndex('custname.ndx','Name', [ixCaseInsensitive]);


Each time the TDbf is opened, the index file must be loaded:

    MyDbf.OpenIndexFile('custname.ndx');


And indexes must be referenced including the extension:

    MyDbf.IndexName := 'custname.ndx';


Index files are packed separately using:

    MyDbf.CompactIndexFile('custname.ndx');

Cómo enlazar TDbf a componentes de datos

The above examples show how to create a new database table in code. Using that table is even more simple.

Data aware components in Lazarus (such as the TDbEdit control) link to a TDataSource component using their "DataSource" and "DataField" properties. The TDataSource component handles communication between the database engine and the data aware components. A TDataSource then links to the TDbf component using it's "DataSet" property. The connection looks like this:

TDbEdit-------
             |
TDbEdit------|-->TDataSource-->TDbf
             |
TDbNavigator--


Be sure to set the FilePath (or FilePathFulll), TableLevel, and TableName properties of your TDbf component before calling

TDbf.Active := True;


There is much more that can be said about programming with databases in Lazarus, and I would recommend a good Delphi database programming book or two as the underlying concepts are the same. I constantly refer to my copy of "Delphi 2 Unleashed" because the concepts and basic code haven't changed much in 8 years.

Empaquetar y reconstruir índices

When a record is deleted, it's not truly removed from the physical table. Periodically you must "pack" a table to recover that lost space. This should be done with exclusive mode set.

MyDbf.Exclusive := True;
MyDbf.Open;
MyDbf.PackTable;
// let's also rebuild all the indexes
MyDbf.RegenerateIndexes;
MyDbf.Close;
MyDbf.Exclusive := False;

Relaciones de tabla principal

Real power in database programming begins when you have multiple tables that reference each other. While TDbf does not yet support referential integrity, it does support a master / detail relationship between TDbf's.

When there are two tables related, for instance:

[customers]
Id       <----|
Name          |
Phone         |
Address       |
              |  The CustID in invoices references a customer primary  field
[invoices]    |
Id            |
Amount        |
CustID   -----|  * This field indexed as "idxcustid"


If you wanted to display all invoices for a given customer, the detail table (invoices) can stay in sync with the master table (customers) automatically.

On the invoices TDbf component set the following:

InvDbf.IndexName := 'idxcustid'; // our field that will match the customers table ID
InvDbf.MasterSource := dsCustomers; // datasource that is linked to the customers TDbf
InvDbf.MasterFields := 'Id'; // field on the customers table we are matching against our index


Programa de ejemplo - navegador DB

I've written a simple application that will use the TDbf to open and display database tables using the dbGrid control. The Linux executable along with project sources which should compile fine in Windows is available from: tony.maro.net

A tener en cuenta

Currently there is no support for referential integrity, or internally encrypted .dbf files.