Lazarus Tdbf Tutorial/ru

From Lazarus wiki
Jump to navigationJump to search

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

Overview

Это руководство описывает основы разработки баз данных с использованием компонента TDbf (by Micha Nelissen) в Lazarus. Дополнительная документация по TDbf также доступна. Эта страница была создана Tony Maro но другие контрибьюторы также приветствуются!

Документацию компонента TDbf в формате pdf смотрите на SourceForge. Полезно сохранить этот pdf и обращаться к нему по мере прочтения этой статьи.

Что нам понадобится

Этот документ был написан с версией Free Pascal Compiler 2.3.1 /Lazarus 0.9.23.

Пакет DbfLaz установлен по умолчанию.

Что обеспечивает TDbf

TDbf обеспечивает доступ к таблицам баз данных dBase и FoxPro для Lazarus (и других IDE), учитывая чтение, запись и создание dBase III +, dBase IV, Visual dBase VII и FoxPro таблиц. Все это делается без использования дополнительных библиотек или движков базы данных. Просто разместите компонент TDbf на вашей форме, и Вы имеете мгновенный доступ в окружающей среде базы данных на разных платформах. TDbf работает и в Windows и в Linux используя Лазарус.

Как создать новую таблицу базы данных

Поскольку для Lazarus нет приложения наподобии "Database Desktop", мы должны создать новую базу данных в коде.

Установка пути

Хорошей мыслью будет выделение для базы данных Вашего приложения собственного каталога. Это упростит резервирование данных. Есть два варианта установки пути. Вы можете установить полный путь используя свойство FilePathFull, или установить путь относительно пути приложения с помощью свойства FilePath. Нипример, установка "FilePath" во время выполнения к "data/" будет использовать субдиректорию data только в директории исполнимого файла. Установка свойства "FilePathFull" к "/var/data/" будет размещать точно по указанному пути, игнорируя расположение приложения.

Выбор TableLevel

По умолчанию, TDbf создает таблицы dBase IV. Хотя это и наиболее совместимо, некоторые возможности, которые Вам могут понадобиться, не поддерживаются. Для поддержки автоинкрементных полей вы должны использовать кое-что поновее. Типы таблиц могут быть следующими::

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

Вы выбираете тип таблицы установкой свойства TableLevel соответственно.

Добавление полей

Создание полей для Вашей новой таблицы во время выполнения в большинстве следует старому стандарту Delphi. Как только вы установили свои значения для свойств FilePath, TableLevel, и TableName, манипулируйте свойством FieldDefs чтобы определить структуру. Например:

MyDbf.FilePathFull := '/location/to/my/data';
MyDbf.TableLevel := 7;
MyDbf.TableName := 'customers.dbf'; // примечание: действительно ли необходимо .dbf?
With MyDbf.FieldDefs do begin
  Add('Id', ftAutoInc, 0, True);
  Add('Name', ftString, 80, True);
End;

Типы полей определены как:

  • 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

Выделенные жирным типы полей поддерживаются

Идем дальше и создаем!

Как только вы определили поля, которые желаете использовать в вашей новой таблице, вы можете идти дальше и создать таблицу:

   MyDbf.CreateTable;

Как добавить индексы в таблицу

Если Ваша база данных состоит из большого числа записей, Вам может понадобиться определить индексы чтобы осуществлять более быстрый поиск по таблице. Чтобы изменить структуру индексов таблицы, мы должны иметь эксклюзивный доступ к таблице - который мы так или иначе име ли бы, создавая таблицу.

       MyDbf.Exclusive := True;
       MyDbf.Open;

Теперь, нам необходимо просто добавить индексы.

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

Put it all together and you get...

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;

Внешние индексные файлы

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');

Как присоединить TDbf к компонентам data-aware

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.

Упаковка и перестройка таблиц

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;

Master table relations

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


Примерное приложение - DB Browser

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

Things you need to be aware of

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