维基副本镜像

这是 pascal.chat 维基的镜像。编辑、历史记录和登录都在那里。

Databases/zh CN

Deutsch · English · Español · Français · Italiano · Português · Русский · 中文(中国) · 日本語

介绍

本页面介绍了Lazarus和数据库。下表提供了所支持的数据库。

警告:你应该只安装已经安装过客户端的数据库组件(如果数据库支持客户端支持)。否则Lazarus可能无法启动,因为丢失文件。那么你将不得不重新安装Lazarus,因为你不能卸载组件。

数据库支持

数据库 包名 需要客户端库? 需要服务端? 支持版本 支持平台
Advantage TAdsDataSet 是 否 10.1 及以上 i386: Linux, Win32
DBase DBFLaz 否 否 III+, IV, VII 所有
In memory memds 否 否 - 所有
In memory bufdataset 否 否 - 所有
Interbase SQLdb 是 是 4 - 6 i386: Linux, Win32
Firebird SQLdb 是 取决于<sup>1</sup> 1 - 2.5 i386: Linux, Win32
(Visual) FoxPro DBFLaz 否 否 2.0, 2.5, 3.0 (不完全) 所有
Microsoft SQL Server SQLdb 是 是 6- FPC 2.6.2+. Linux, macOS, Win32, probably *BSD, probably Solaris<sup>2</sup>
MySQL SQLdb 是 是 3.0 - 5.5 i386: Linux, Win32
ODBC SQLdb 是 取决于 3.x <sup>3</sup> i386: Linux, Win32
Oracle SQLdb 是 是 - -
Paradox TParadoxDataSet 否 否 up to Table Level 7 (and up ??) 所有
PostgreSQL SQLdb 是 是 6.6 - 8 i386: Linux, Win32
Sybase Adaptive Server Enterprise (ASE) SQLdb 是 是 任何 Linux, macOS, Win32, probably *BSD, probably Solaris<sup>2)</sup>
SQLite SQLdb 是 否 sqlite3 i386: Linux, Win32
SQLite TSQLite3Dataset 是 否 sqlite2,sqlite3 i386: Linux, Win32
Text 文件 sdf 否 否 - 所有

备注 (1): 你可以使用 Firebird 对Windows和Linux的嵌入式版本(可能在Mac OS X也行),也可以连接到基于Windows/Unix/macOS/FreeBSD的/其他运行 Firebird 服务器支持的平台

备注 (2): 这些连接器使用FreeTDS 的库作为驱动程序,FreeTDS 文档表明,应该建立这些平台。Windows x86/x64可以在这里下载:1 和 2

备注 (3): 此版本号指的是ODBC标准,而不是一个驱动程序或驱动程序管理器的版本号。ODBC 3.x驱动对于大多数DBMS。

数据库客户端绑定

If you want to use one of the databases that need client libraries, those libraries have to be installed. Not only on the computer you're programming on, but also on the computers where the application must run. Note that some databases (in particular MySQL) only work if the bindings which are compiled in the application are from the same version as those of the installed libraries. You can find out how to install those libraries (.so files on *nix systems, and .dlls on windows) on the website of the database developers. The binding units can be found in the packages/base directory in the fpc-sources. They basically consist of the client API calls like mysql_connect_database, which are completely different for each database. It is possible to write database applications using these units, but it is usually far more work and bug-sensitive than using the DB-unit Lazarus components.

Most of these bindings packages are hard-linked to the client libraries. This means that if the application is compiled with one of these units in it, the whole application can not be linked if the client libraries are not available on the workstation. This means that your program executable will not be generated if you do not have installed - for example - a MySQL client on your computer, and you are using the mysql4.pp unit in your program. If you succeed in compiling the program on a computer which has the MySQL client libraries installed, it still won't start on any other machine without the appropriate MySQL client libraries. In other words: for these databases, you need to install client libraries on your development machine, and you need to install these client libraries with your application.

To avoid such problems some of the packages are also able to link dynamically to the libraries. Before any calls to those libraries can be made, the unit has to be 'initialized'. This initialization fails if the database client isn't installed on the computer. If the program is ready using the client library, the unit has to be 'released'.

数据集

Database use in Lazarus (or Free Pascal) is fundamentally based on the TDataset class. This represents a table or query to your application. However, like many other such fundamental classes, you don't use the TDataset class itself, you use a descendant of it. There are many of these. They provide access to different kinds of databases, such as local dbase or text files, or back-end databases such as PostgreSQL, Firebird, MySQL and so forth. Some dataset descendants link directly to database tables, while others use additional components or libraries to perform the link.

Dataset descendants, being non-visual components are (usually) part of the Free Component Library (FCL) rather than the Lazarus Component Library (LCL).

Datasets can be used both programmatically and with visual controls. A typical Lazarus database application will often use both methods. In either case, the first step is to create the TDataset descendant, initialise it to connect to the table or query you want, and open it. This can be done either in code at run time or by putting a component on your form and setting it's properties at design time. The details of this vary considerably with different TDataset descendants, so see the various guides under Databases for what has to be done for your database.

When the dataset is opened, a set of field components are created, one for each field or column of the table or query you opened. Each field component is a descendant of TField, appropriate to the particular data type of the field, eg, TStringField.

使用数据集代码

Programmatic access will be explained in more detail in Using Dataset and Field components, but as a very simple overview:

See Database field type for a list of field types.

使用可视化(数据感知)控制

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:

See #Data Controls below for more details on the controls

数据集状态

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.

数据集 UpdateStatus

UpdateStatus determines the current state of the record buffer, if updates have not yet been applied to the database.

Example how to detect if ApplyUpdates will Insert, Update or Delete data:

pascal
procedure QueryAfterPost(DataSet: TDataSet);
begin
  case DataSet.UpdateStatus of
    usUnmodified : ShowMessage('Unmodified');
    usModified   : ShowMessage('Modified');
    usInserted   : ShowMessage('Inserted');
    usDeleted    : ShowMessage('Deleted');
  end;
end;

Value Explanation:

提交和取消

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

插入新记录

To insert a new record into a TDataset descendent, one should use the method Insert. After that one can set the field values and then finally call Post to commit the new record, as the example below shows.

The example also shows how to insert BLOB data from a file - you can also use LoadFromStream to load the data from a stream.

pascal
  MyDataset.Insert;
  MyDataset.Fields[0].AsInteger := 4; //an integer field
  MyDataset.Fields[1].AsString := 'First Name'; //a string field
  TBlobField(MyDataset.Fields[2]).LoadFromFile('SomeBlobfile.bin'); //blob field
  MyDataset.Post;

如何快速跳转到特定记录

选择所有记录

If you use SELECT * FROM to select all records of the table and then desires to quickly jump between them, you will have to build an index and search on it. It is more efficient to select only the record that you want.

选择所需记录

One fast solution to jump to a particular record is to select only it, for example doing:

pascal
var
  MyDataset: TSQLQuery;
begin
  //...
  MyDataset.FieldDefs.Add('SessionId', ftLargeint);
  MyDataset.FieldDefs.Add('GameEvent', ftLargeint);
  MyDataset.FieldDefs.Add('TableId', ftInteger);
  MyDataset.FieldDefs.Add('LoggedIn', ftBoolean);
  MyDataset.FieldDefs.Add('PlayerId', ftInteger);
  MyDataset.Active := False;
  { Non-parameterized format; may run into issues with text containing ' and dates
  SQLText := Format('select * from "GameSession" WHERE "SessionId"=%d', [ASessionId]);
  }
  // Solution: parameterized query:
  // Actually, if this is done in a loop, you only need to set the SQL.Text once,
  // and only change the parameter value
  MyDataset.SQL.Text := 'select * from "GameSession" WHERE "SessionID"=:SessionID');
  MyDataSet.ParamByName('SessionID').AsLargeInt := ASessionID;
  try
    MyDataset.Active := True;
  except
    //...
  end;

You can then read information using something like this:

pascal
 lPlayerId := MyDataset.Fields[4].AsInteger;

过滤

You can filter your dataset to restrict the records to a subset you want (e.g. all surnames starting with Smith).

定位/查找

Although more often used in non-SQL datasets (e.g. Paradox, TDBF) you can jump between records using locate/lookup.

使用 TSQLQuery

For more information about TSQLQuery see Working With TSQLQuery

导出

FPC/Lazarus contains functionality to let you export datasets to various formats; see e.g.

Of course, you could also do it manually (see e.g. FPSpreadsheet#Converting_a_database_to_a_spreadsheet for export to Excel format using fpspreadsheet)

数据控制

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.

数据源控制

This control keeps track of which record the linked controls currently are on. The datasource contorl must be linked to a dataset (e.g. a TSQLQuery).

单字段控制

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.

Apart from the mentioned documentation, some more detail can be found here: Grids Reference Page#TCustomDBGrid

Navigator Control

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

Key Properties:

运行FPC数据库测试

Free Pascal database components include a fpcunit-based test framework, dbtestframework, that can be used to verify functionality. See the directory source\packages\fcl-db\tests\ in your FPC source tree. Included is a test framework that can be run on various database components, as well as some other tests (e.g. test of database export).

To run the test framework on a certain database:

1. 保存 source\packages\fcl-db\tests\database.ini.txt as source\packages\fcl-db\tests\database.ini

2. 修改 source\packages\fcl-db\tests\database.ini to choose which database type you will use.

Example for Interbase/Firebird:

ini
[Database]
type=interbase

3. In the same file, customize settings for your database. E.g. if you chose interbase before:

ini
[interbase]
connector=sql
connectorparams=interbase
; Database name/path (note: database needs to exist already)
; You can use aliases (see aliases.conf in your Firebird documentation)
name=testdb
user=sysdba
password=masterkey
; your hostname may very well differ:
; Leave blank if you want to use an embedded Firebird database
hostname=192.168.0.42

4. Compile and run source\packages\fcl-db\tests\dbtestframework.pas (You can also use Lazarus to compile and run the GUI version, dbtestframework_gui) If you are using an embedded database on Windows (e.g. Firebird embedded or sqlite), copy the required DLL files to the directory first. The output will be in XML format (or displayed on your screen if you use dbtestframework_gui).

Please see source\packages\fcl-db\tests\README.txt for more details.

Lazarus包含数据库包

sqldblaz.lpk

This package provides access to different databases. These include:

The components (TSQLQuery, TSQLTransaction, TIBConnection, TODBCConnection, TOracleConnection, TMSSQLConnection, TMySQL40Connection, TMySQL41Connection, TMySQL50Connection, TPQConnection, TSybaseConnection) are on the 'SQLdb' tab in the component palette.

dbflaz.lpk

This package provides access to dBase and FoxPro databases. You can get more information in the Lazarus Tdbf Tutorial. The TDbf component is on the 'Data Access' tab in the component palette.

sqlitelaz.lpk

This package provides access to SQLite databases. You can get more information in the Lazarus Database Overview.

sdflaz.lpk

The component TSdfDataSet can be found on the 'Data Access' tab in the component palette.

lazreport.lpk

The homepage of the report generator is http://lazreport.sourceforge.net/. More informationen (et al. an additional link) can be found here. LazReport depends on the Printer4Lazarus package. With revision 11950 LazReport was included in the Lazarus SVN repository.

外部包/库

Zeos 数据库对象

These components provide access to different databases. You can find more information here. This wiki also contains a Zeos tutorial.

Pascal 数据对象

There is now an alternative.

支持:

like prepared statements, binding, and stored procedures are supported by database API called Pascal Data Objects, which is inspired by PHP Data Objects. All the code and documentation necessary to use this new API is available on Sourceforge:

http://pdo.sourceforge.net

TPSQL

These components provide access via TCP/IP to PostgreSQL databases. You can find more information on this page.

FIBL

These components provide access to Interbase and Firebird databases. The homepage is http://sourceforge.net/projects/fibl.

IBX

IBX For Lazarus are components to access Firebird databases: see IBX

FBLib Firebird 库

FBLib is an open Source Library No Data Aware for direct access to Firebird Relational Database from Borland Delphi/Kylix, Free Pascal and Lazarus.

Current Features include:

You can download documentation on FBLib's website.

Unified Interbase

UIB provides access to Interbase, Firebird and YAFFIL databases. The homepage is [http://www.progdigy.com](http://www.progdigy.com)) A svn repository is available under https://uib.svn.sourceforge.net/svnroot/uib .

TechInsite Object Persistence 框架 (tiOPF)

More information about tiOPF can be found on this page.

Advantage TDataSet Descendant

The Advantage TDataSet Descedant provides a means of connecting to (and opening tables with) the Advantage Database Server. Advantage is a flexible, administration-free embedded database that provides Client/Server as well as Peer-to-peer access to Clipper, FoxPro and Visual FoxPro 9 DBF file formats, as well as a proprietary file format that provides a migration path allowing the use of newer features.

Key Features:

For more information, see the Advantage Database Server website.

ZMSQL, sql-enhanced 内存数据库

For more information, see the ZMSQL wiki page

ZMSQL is an open source, TBufDataset descendant SQL enhanced in-memory database for Free Pascal (FPC), operating with semicolon-separated values flat text tables. Completely written in Pascal, it has no dependencies on external libraries. It uses JanSQL engine for SQL implementation.

它提供了:

The download contains the source code, some demo applications illustrating the features of the component as well as a readme.

参见


From the Free Pascal wiki, page "Databases/zh CN", as it stood on 2020-02-16 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

版本2,最后由WikiArchive于修改。