Databases/ru

From Lazarus wiki
Jump to navigationJump to search

Deutsch (de) | English (en) | español (es) | italiano (it)

Цель

Эта страница освещает общие вопросы работы с базами данных в Lazarus и является начальной информацией для программистов, которые хотят написать программу, работающую с базами данных.

Dataset'ы (Наборы данных)

Базы данных в Lazarus (или FreePascal) основывают свою работу на базовом классе TDataset. Этот класс представляет таблицу или результат запроса в Вашем приложении. Как и многие другие базовые классы, Вы не можете использовать TDataSet в своём приложении непосредственно, а используете только его потомков, которых довольно много. Они обеспечивают доступ к различным видам баз данных, таким как локальный dbase или текстовые файлы, а так же серверами баз данных, таких как PostgreSQL, Firebird, MySQl и т.п. Некоторые потомки TDataSet связываются непосредственно с таблицами базы данных, в то время как другие используют дополнительные компоненты или библиотеки.

Обратитесь кстранице Databases для получения более полной информации об этом.

Потомки Dataset, будучи невизуальными компонентами, обычно являются частью Free Component Library (FCL) а не Lazarus Component Library (LCL).

Использование Dataset'ов

Dataset'ы можно использовать и программно, и в качестве визуальных компонентов. Типичное приложение баз данных в Lazarus использует оба метода. В общем случае, первым шагом нужно выбрать соответствующего потомка TDataset для выбранной Вами базы данных, создать подключение, выбрать таблицу или создать запрос и открыть его. Это может быть сделано или в коде, во время выполнения, или помещая компонент на Вашу форму и устанавливая соответствующие свойства во времени разработки. Детали этой операции могут значительно различатся для разных потомков TDataset, так что подробности смотрите в Databases для выбранной Вами базы данных.

Когда набор данных открыт, создаётся ряд компонентов, по одному для каждого поля или столбца таблицы (запроса). Каждый компонент поля - это потомок TField, соответствующий специфическому типу данных этого поля, например, TStringField.

Использование dataset'ов в коде программы

О программном доступе объясняется более подробно в Using Dataset and Field components, вот краткий обзор:

  • Используйте потомок TDataset чтобы открыть таблицу или запрос, отфильтруйте те строки, которые хотите видеть и двигайтесь от строки к строке.
  • Используйте потомок TField для:
    • Доступа к общей информации о поле.
    • Доступа к данным текущей строки. (используя свойство AsХХХХ, например AsString, AsInteger и так далее.)
  • Используйте для обращения к полям потомка TDatasetтак же:
    • Свойство fields, к примеру Fields[0] для самого первого поля,
    • Метод FieldByName, как пример FieldByName('AGE') вернёт поле, которое в базе данных называется 'AGE'.

Использование визуальных (db-ориентированных) компонентов

To use databases in a simple, "RAD" style Lazarus application, you usually configure the dataset descendant at design time and the use the data-aware controls. To do this:

  • Add the dataset descendant for the database of your choice, together with any supporting components, to your form, and open it (Set the 'Active' property to true)
  • Add a TDatasource component (from the "Data Access" tab) to the form, and "link" it to the dataset (set the DataSet property)
  • Add data-aware controls from the "Data Controls" tab to the form, and link each one to the DataSource (not dataset) component
  • Most controls link to a single field, so you also need to set the Field for each tab.

See #Data Controls below for more details on the controls

Рабочие состояния Dataset

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.

Принятие и отмена изменения

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 dataset 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.

Визуальные компоненты для работы с данными

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.

Компоненты для работы с одним полем

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

Компонент DBGrid

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

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)