Lazarus Tdbf Tutorial/es

From Lazarus wiki
Revision as of 07:55, 21 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)


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

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

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

Creating fields for your new table at runtime pretty much follows the old Delphi standard. Once you have set your FilePath, TableLevel, and TableName properties, manipulate the FieldDefs property to set up the structure. For example:

MyDbf.FilePathFull := '/location/to/my/data';
MyDbf.TableLevel := 7;
MyDbf.TableName := 'customers.dbf'; // note: is the .dbf really required?
With MyDbf.FieldDefs do begin
  Add('Id', ftAutoInc, 0, True);
  Add('Name', ftString, 80, True);
End;

Field types are defined as:

  • 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

Bold types are currently supported

¡Continuar y crearla!

Once you have defined the fields you wish to use in your new table, you can go ahead and create it with:

   MyDbf.CreateTable;

Como añadir índices a una tabla

If your database is larger than a few records, chances are you will want to have indexes defined to make searching faster. To change the index structure of a table, we will want to have exclusive access to the table - which we would have while creating it anyway.

       MyDbf.Exclusive := True;
       MyDbf.Open;

Now, we just have to add the index.

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

Póngalo todo junto y tendrá...

The following sample creates a new table "customers" in code. This of course only needs done once, and after that you just OPEN the table, don't create it ;-)

{ We will require the following units be in the USES clause: }
{ uses Dbf, db, Dbf_Common                                   }
{ The Dbf is put there when you drop the TDbf on a form...   }
{ but you will need db for the DataSet object and Dbf_Common }
{ for things such as the field type definitions              }
var
  MyDbf: TDbf;
begin
  MyDbf := TDbf.Create(nil);
  try
    { use relative path to "data" directory }
    MyDbf.FilePath := 'data/'; 
    { we want to use Visual dBase VII compatible tables }
    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.