mysql/pl

From Lazarus wiki
Revision as of 13:18, 3 February 2021 by Slawek (talk | contribs) (→‎Spraw, aby MySQL działał dla FPC w trybie tekstowym: tłumaczenie na j. polski cd.)
Jump to navigationJump to search

English (en) español (es) français (fr) polski (pl)

Databases portal

References:

Tutorials/practical articles:

Databases

Advantage - MySQL - MSSQL - Postgres - Interbase - Firebird - Oracle - ODBC - Paradox - SQLite - dBASE - MS Access - Zeos

Przegląd

Możesz użyć Free Pascal/Lazarus, aby uzyskać dostęp do serwera bazy danych MySQL.

Win64: zobacz ostrzeżenie tutaj dotyczące nieużywania niektórych wersji FPC/Lazarus Win64.

Zalety MySQL:

  • Jest bardzo szeroko stosowany i dostępny
  • Chociaż starsze wersje miały zasłużoną opinię, że nie są prawdziwymi RDBMS, nowsze wersje obsługują właściwości ACID, jeśli są prawidłowo skonfigurowane (z odpowiednim zapleczem pamięci)

Wady MySQL:

  • Opiekunowie MySQL łamią binarną kompatybilność między wersjami bibliotek klienta. Oznacza to, że dla każdej nowej wersji trzeba wykonać tłumaczenie FPC/Lazarus, co spowalnia działanie.
  • Licencja może być ograniczona dla niektórych użytkowników (np. We wdrożeniach komercyjnych). Istnieją kompatybilne, prawdopodobnie mniej restrykcyjne alternatywy, takie jak MariaDB.

Z tego powodu wielu użytkowników Lazarusa/FPC preferuje bazy danych Firebird lub PostgreSQL.

Licencjonowanie MySQL

Przed znaczącym wdrożeniem MySQL nie zapomnij przeczytać jej licencji.

SQLDB

Lazarus 1.2 (z FPC 2.6.2), obsługuje

  • Biblioteka klienta MySQL 4.0
  • Biblioteka klienta MySQL 4.1
  • Biblioteka klienta MySQL 5.0
  • Biblioteka klienta MySQL 5.1
  • Biblioteka klienta MySQL 5.5 (obsługiwana od wersji Lazarus 1.0.8)
  • Biblioteka klienta MySQL 5.6 (obsługiwana od Lazarusa ?)

sqldbcomponents2.png

Nowsze wersje FPC/Lazarus mogą obsługiwać nowsze biblioteki klienta MySQL.

Upewnij się, że używasz odpowiedniego komponentu połączenia dla swojej wersji biblioteki klienta. Więc jeśli masz zainstalowane biblioteki klienta dla MySQL 4.1, musisz użyć komponentu TMySQL41Connection, nawet jeśli serwer działa w wersji 4.0 lub 5.0. Powodem tego jest to, że biblioteki klienckie MySQL często łamią kompatybilność ich API, więc każda wersja wymaga innego sterownika Pascala.

W systemach typu *nix kod SQLDB może szukać zwykłej wersji biblioteki bez sufiksów numerów wersji. Możesz sobie z tym poradzić na kilka sposobów:

  • (w wielu Linuksach) zainstalowanie biblioteki w wersji -dev
  • utworzenie dowiązania symbolicznego twojej konkretnej nazwy biblioteki do tej, której szuka FPC (raczej hakerskie)
  • użycie TSQLDBLibraryLoader, aby określić nazwę biblioteki przed załadowaniem połączenia

Samouczki SQLDB i przykładowy kod

BigChimp wrzesień 2012: uwaga: wiele z tych samouczków to zduplikowany kod i można je skonsolidować. Proponuję przenieść jak najwięcej do samouczka SQLDB zorientowanego na GUI i utworzyć osobną stronę samouczka bazy danych FPC, aby utworzyć przykład trybu tekstowego

Uruchom serwer MySQL działający w systemie Linux lub Windows

Postępuj zgodnie z instrukcjami zawartymi w podręczniku użytkownika MySQL. Upewnij się, że demon mysqld działa niezawodnie i że wszyscy potencjalni użytkownicy (w tym root, mysql, Ty i wszyscy inni, którzy mogą tego potrzebować) mają tyle uprawnień, ile potrzebują, z tylu hostów, ile potrzeba (takich jak 'localhost', nazwa hosta lokalnego i inne hosty w twojej sieci), o ile jest to zgodne z bezpieczeństwem. Zaleca się, aby wszyscy użytkownicy, w tym root, mieli hasła. Przetestuj działanie systemu bazy danych, korzystając z przykładów podanych w instrukcji i sprawdź, czy wszyscy użytkownicy naprawdę mają niezawodny dostęp.

Spraw, aby MySQL działał dla FPC w trybie tekstowym

W katalogu $(fpcsrcdir)/packages/base/mysql/ znajduje się przykładowy program. Możesz znaleźć katalog ze źródłami fpc w Lazarusie: Narzędzia -> Opcje -> Pliki -> Katalog źródłowy FPC. Możliwe ścieżki do katalogu mysql to /usr/share/fpcsrc/packages/base/mysql/ (rpm install) lub C:\lazarus\fpcsrc\packages\base\mysql\ (windows). Ten katalog zawiera również moduły mysql.pp, mysql_com.pp i mysql_version.pp. Przed uruchomieniem skryptu testowego musisz utworzyć bazę danych o nazwie testdb: zrób to, logując się do monitora mysql (jako root z pełnymi uprawnieniami) i wydając następującą instrukcję SQL:

CREATE DATABASE testdb;

następnie upewnij się, że wszyscy właściwi użytkownicy mają do niego odpowiednie uprawnienia dostępu

GRANT ALL ON testdb TO johnny-user IDENTIFIED BY 'johnnyspassword';

Istnieje skrypt o nazwie mkdb, który powinieneś teraz spróbować uruchomić:

sh ./mkdb

Prawdopodobnie zakończy się to niepowodzeniem, ponieważ system nie pozwoli anonimowemu użytkownikowi uzyskać dostęp do bazy danych. Zmień więc skrypt za pomocą edytora tak, aby wiersz wywołujący mysql brzmiał:

mysql -u root -p  ${1-testdb} << EOF >/dev/null

i spróbuj uruchomić go ponownie, wprowadzając hasło po wyświetleniu monitu. Przy odrobinie szczęścia mogłeś stworzyć testową bazę danych: przetestuj ją (będąc zalogowanym do monitora mysql), wydając instrukcję mysql

select * from FPdev;

Powinieneś zobaczyć tabelę zawierającą ID, nazwę użytkownika i adres e-mail niektórych programistów FPC.

Teraz spróbuj uruchomić program testowy testdb.pp (może to wymagać skompilowania i prawie na pewno zakończy się niepowodzeniem przy pierwszej próbie !!).

Zauważyłem, że program nie mógł połączyć się z mysql z kilku powodów:

  • Mój system (SuSE Linux v9.0) instaluje mysql v4.0.15, a nie wersję 3, dla której pakiet został zaprojektowany.
  • Program musi mieć nazwy użytkowników i hasła, aby uzyskać dostęp do bazy danych.
  • Kompilator musi wiedzieć, gdzie znaleźć biblioteki mysql (JEŚLI NIE ZAINSTALOWAŁEŚ BIBLIOTEK PROGRAMISTYCZNYCH MYSQL, ZRÓB TO TERAZ!)

Utworzyłem kopię pliku testdb.pp o nazwie trydb.pp, zamiast edytować oryginał - oznacza to, że oryginalne pliki nadal są naprawiane w kolejnych aktualizacjach CVS. Skopiowałem również pliki znalezione w podkatalogu mysql/ver40/ do głównego podkatalogu mysql/, zmieniając ich nazwy na mysql_v4.pp, mysql_com_v4.pp i mysql_version_v4.pp, pamiętając o zmianie nazwy modułóww każdym pliku. Zmieniłem instrukcję użycia w trydb.pp na

uses mysql_v4

i oświadczenie w mysql_v4.pp do

uses mysql_com_v4

Dodałem wiersz do /etc/fpc.cfg, aby wskazać moje biblioteki:

-Fl/lib;/usr/lib

Następujący krok może nie być konieczny, jeśli biblioteki deweloperskie są zainstalowane, ponieważ łącza zostaną utworzone za Ciebie, ale sprawdzenie nigdy nie zaszkodzi. Musiałem znaleźć prawdziwą nazwę biblioteki mysqlclint w katalogu /usr/lib i w moim przypadku musiałem wydać polecenie powłoki:

ln -s libmysqlclient.so.12.0.0 lmysqlclient

aby utworzyć dowiązanie symboliczne umożliwiające FPC znalezienie biblioteki. Na wszelki wypadek stworzyłem też link

ln -s libmysqlclient.so.12.0.0 mysqlclient

i umieściłem podobne linki w różnych innych katalogach: nie jest to absolutnie konieczne, ale na wszelki wypadek ...! Niektórzy użytkownicy mogą potrzebować dodać następujące łącze:

ln -s libmysqlclient.so.12.0.0 libmysqlclient.so

Zmodyfikowałem trydb.pp, aby zawierał dane użytkownika, początkowo dodając hosta, użytkownika i hasło jako stałe Pchar:

const
  host : Pchar= 'localhost';
  user : Pchar= 'myusername';
  passwd: Pchar = 'mypassword';

Template:Ostrzeżenie Odkryłem również, że nie mogę połączyć się z mysql za pomocą wywołania mysql_connect(), ale musiałem użyć mysql_real_connect(), który ma o wiele więcej parametrów. Aby jeszcze bardziej skomplikować sprawę, wydaje się, że liczba parametrów zmieniła się między wersją 3 (w której jest siedem) a wersją 4 (w której jest osiem). Przed użyciem mysql_real_connect musiałem użyć mysql_init(), którego nie ma w oryginalnym mysql.pp, ale znajduje się w mysql_v4.pp.

Tak więc kod do połączenia z bazą danych to teraz:

{ kilka dodatkowych zmiennych }
var
  alloc : PMYSQL;
  
{fragment głównego programu}
  
begin
  if paramcount=1 then
  begin
    Dummy:=Paramstr(1)+#0;
    DataBase:=@Dummy[1];
  end;
  
  Writeln('Przydzielanie miejsca ...');
  alloc := mysql_init(PMYSQL(@qmysql));
  Write('Łączę się z MySQL ...');
  sock := mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
  if sock=Nil then
  begin
    Writeln(stderr,'Nie można połączyć się z MySQL');
    Writeln(stderr, 'Błąd: ', mysql_error(@qmysql));
    halt(1);
  end;
  Writeln('Gotowe.');
  Writeln('Parametry połączenia:');
 {$ifdef Unix}
  writeln('Mysql_port      : ',mysql_port);
  writeln('Mysql_unix_port : ',mysql_unix_port);
 {$endif}
  writeln('Host info       : ',mysql_get_host_info(sock));
  writeln('Server info     : ',mysql_stat(sock));
  writeln('Client info     : ',mysql_get_client_info);
  
  Writeln('Wybór bazy danych ',DataBase,'...');
  if mysql_select_db(sock, DataBase) < 0 then
  begin
    Writeln(stderr,'Nie udało się wybrać bazy danych ',Database);
    Writeln(stderr,mysql_error(sock));
    halt(1);
  end;
 {... dalej oryginalna zawartość pliku testdb.pp}

Teraz - gotowy do rozpoczęcia kompilacji trydb.pp?

 fpc trydb

sukces! Teraz uruchom to:

 ./trydb

Super! Mam listę twórców FPC!

Kilka dodatkowych ulepszeń: uczyń wprowadzanie danych użytkownika i poleceń mysql interaktywnymi, używając zmiennych zamiast stałych, i pozwól na wprowadzenie kilku poleceń SQL, dopóki nie wydamy polecenia quit: zobacz pełna lista programów, gdzie dane użytkownika są wprowadzane z konsoli, a program przechodzi w pętlę, w której z konsoli wprowadza się polecenia SQL (bez średnika terminala) i wypisuje odpowiedzi, aż do wpisania „quit” z klawiatury.

Zobacz przykładową lista konsoli.

Connecting to MySQL from a Lazarus Application

This tutorial shows how to connect Lazarus to the MySQL database, and execute simple queries, using only the basic Lazarus components; it uses no Data Aware components, but illustrates the principles of interfacing with the database.

Create a new project in Lazarus:

Project -> New Project -> Application

A new automatically generated Form will appear.

Enlarge the form to fill about half of the screen, then re-name the form and its caption to 'TryMySQL'.

From the Standard Component tab place three Edit Boxes on the upper left side of the Form, and immediately above each box place a label. Change the names and captions to 'Host' (and HostLLabel,HostEdit), 'UserName' (and UserLabel, UserEdit) and 'Password' (with PasswdLabel and PasswdEdit). Alternatively you could use LabelledEdit components from the Additional tab.

Select the Passwd Edit box and find the PasswordChar property: change this to * or some other character, so that when you type in a password the characters do not appear on your screen but are echoed by a series of *s. Make sure that the Text property of each edit box is blank.

Now place another Edit box and label at the top of the right side of your form. Change the label to 'Enter SQL Command' and name it CommandEdit.

Place three Buttons on the form: two on the left under the Edit boxes, and one on the right under the command box.

Label the buttons on the left 'Connect to Database' (ConnectButton)and 'Exit' (ExitButton) and the one on the right 'Send Query' (QueryButton).

Place a large Memo Box labelled and named 'Results' (ResultMemo) on the lower right, to fill most of the available space. Find its ScrollBars property and select ssAutoBoth so that scroll bars appear automatically if text fills the space. Make the WordWrap property True.

Place a Status Bar (from the Common Controls tab) at the bottom of the Form, and make its SimpleText property 'TryMySQL'.

A screenshot of the Form can be seen here: Mysql Example Screenshot

Now we need to write some event handlers.

The three Edit boxes on the left are for entry of hostname, username and password. When these have been entered satisfactorily, the Connect Button is clicked. The OnCLick event handler for this button is based on part of the text-mode FPC program above.

The responses from the database should be converted into strings and displayed in the Memo box. Text mode Pascal write and writeln statements are capable of performing a lot of type conversion 'on the fly', but the use of a memo box for text output requires explicit conversion of data types to the correct string: so Pchar variables have to be converted to strings using StrPas, and integers have to be converted with IntToStr.

Strings are displayed in the Memo box using:

procedure ShowString(S : string);
(* display a string in a Memo box *)
begin
  trymysqlForm1.ResultsMemo.Lines.Add(S)
end;

The ConnectButton event handler thus becomes:

procedure TtrymysqlForm1.ConnectButtonClick(Sender: TObject);
(* Connect to MySQL using user data from Text entry boxes on Main Form *)
var strg: string;
  
begin
  dummy1 :=  trymysqlForm1.HostEdit.text+#0;
  host := @dummy1[1];
  dummy2 := trymysqlForm1.UserEdit.text+#0;
  user := @dummy2[1] ;
  dummy3 := trymysqlForm1.PasswdEdit.text+#0;
  passwd := @dummy3[1] ;

  alloc := mysql_init(PMYSQL(@qmysql));
  sock :=  mysql_real_connect(alloc, host, user, passwd, database, 0, nil, 0);
  if sock=Nil then
    begin
      strg :='Couldn''t connect to MySQL.'; showstring (strg);
      Strg :='Error was: '+ StrPas(mysql_error(@qmysql)); showstring (strg);
    end
    else
    begin
      trymysqlForm1.statusBar1.simpletext := 'Connected to MySQL';
      strg := 'Now choosing database : ' + database; showstring (strg);
 {$ifdef Unix}
      strg :='Mysql_port      : '+ IntToStr(mysql_port); showstring (strg);
      strg :='Mysql_unix_port : ' + StrPas(mysql_unix_port); showstring (strg);
 {$endif}
      Strg :='Host info       : ' + StrPas(mysql_get_host_info(sock));
      showstring (strg);
      Strg :='Server info     : ' + StrPas(mysql_stat(sock)); showstring (strg);
      Strg :='Client info     : ' + Strpas(mysql_get_client_info);  showstring (strg);
  
      trymysqlForm1.statusbar1.simpletext := 'Selecting Database ' + DataBase +'...';
      if mysql_select_db(sock,DataBase) < 0 then
      begin
        strg :='Couldn''t select database '+ Database; ShowString (strg);
        Strg := mysql_error(sock); ShowString (strg);
      end
    end;
end;

The Text Box on the right allows entry of a SQL statement, without a terminal semicolon; when you are satisfied with its content or syntax, the SendQuery button is pressed, and the query is processed, with results being written in the ResultsMemo box.

The SendQuery event handler is again based on the FPC text-mode version, except that once again explicit type-conversion has to be done before strings are displayed in the box.

A difference from the text-mode FPC program is that if an error condition is detected, the program does not halt and MySQL is not closed; instead, control is returned to the main form and an opportunity is given to correct the entry before the command is re-submitted. The application finally exits (with closure of MySQL) when the Exit Button is clicked.

The code for SendQuery follows:

procedure TtrymysqlForm1.QueryButtonClick(Sender: TObject);
var
  dumquery, strg: string;
begin
  dumquery := TrymysqlForm1.CommandEdit.text;
  dumquery := dumquery+#0;
  query := @dumquery[1];
  trymysqlForm1.statusbar1.simpletext := 'Executing query : '+ dumQuery +'...';
  strg := 'Executing query : ' + dumQuery; showstring (strg);
  if (mysql_query(sock,Query) < 0) then
  begin
    Strg :='Query failed '+ StrPas(mysql_error(sock)); showstring (strg);
  end
  else
  begin
    recbuf := mysql_store_result(sock);
    if RecBuf=Nil then
    begin
      Strg :='Query returned nil result.'; showstring (strg);
    end
    else
    begin
      strg :='Number of records returned  : ' + IntToStr(mysql_num_rows (recbuf));
      Showstring (strg);
      Strg :='Number of fields per record : ' + IntToStr(mysql_num_fields(recbuf));
      showstring (strg);
      rowbuf := mysql_fetch_row(recbuf);
      while (rowbuf <>nil) do
      begin
        Strg :='(Id: '+ rowbuf[0]+', Name: ' + rowbuf[1]+ ', Email : ' +
        rowbuf[2] +')';
        showstring(strg);
        rowbuf := mysql_fetch_row(recbuf);
      end;
    end;
  end;
end;

Save your Project, and press Run -> Run

Download example source code

Warning-icon.png

Ostrzeżenie: Current versions of Lazarus/FPC require committing all MySQL transactions. This was not necessary in earlier versions. The code download likely will not work until it is updated.

A full listing of the program is available here Sample Source Code

Lazarus, MySQL and UTF-8

The following may be required for other codepages/character sets as well

UTF-8 Unicode is a convenient multibyte character set encoding, that allows working with multilingual texts without requiring WideStrings. It is supported both by Lazarus SQLdb components and by MySQL since version 4.1 by choosing the appropriate character set.

However, simply setting this encoding as default for

  • your tables and
  • the MySQL connection component (e.g. TMySQL51Connection.CharSet:='UTF8';)

will result in incorrect storage and retrieval of UTF-8 strings: any accented/international character will show up as question mark (?). Apparently, the reason for this is that MySQL client library is compiled to expect Latin1 character set by default.

In order to enable proper communication between Lazarus, MySQL client library and MySQL server, additional two queries need to be executed each time a connection to the database is established:

SET CHARACTER SET `utf8`

and

SET NAMES 'utf8'

The first query will ensure your application receives strings in correct encoding, and the second tells MySQL not to convert strings it receives from your application.

Simple MySQL Demo Using the TMySQL5xConnection Component

Here is code that functions as a quick demo to get up and running simply. As with all SQLDB components, make sure the database client library is in the correct place:

  • on Windows: the DLL, e.g. libmysql.dll is put in the project output directory (where the executable is generated). Alternatively, you could also place it in your Windows/system32 directory
  • on Linux/OSX: install the mysql client library in your path (e.g. using your distribution's package manager)

When distributing your application, make sure the proper MySQL client library is present on your user's computer. As this can be a problem, perhaps using a different database engine may make more sense.

Code-driven sample

The example below uses code to fill your controls with data. You can also use data-bound controls, which might be quicker/easier. See the example below it or SQLdb_Tutorial1 for this.

Place three edit boxes, a memo box and a few buttons on the form. You need to add mysqlXXconn and sqldb to the uses statement.

In this example, the MySQL DBMS has a user 'root' with no password, and a database 'test1' with table 'tPerson' which has three fields: 'personid' (int), 'surname' (varchar(40)) and 'dob' (datetime). Also, some test data was inserted.

The button btnTest must be clicked first as it creates the connection with the DBMS. Note the line that applies updates - without this the changed or new data will not be written back to the DB though they will be in memory and can be viewed using btnFirst and btnNext.

unit unt_db;
// Example based on:
// http://www.lazarus.freepascal.org/index.php?name=PNphpBB2&file=viewtopic&t=5761
// from tpglemur on that forum
{$mode objfpc}{$H+}
interface
uses
  Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
  mysql50conn, sqldb, StdCtrls;
type
  { TForm1 }
  TForm1 = class(TForm)
    btnTest: TButton;
    btnNext: TButton;
    btnFirst: TButton;
    btnNew: TButton;
    edtPersonID: TEdit;
    edtSurname: TEdit;
    edtDOB: TEdit;
    Memo1: TMemo;
    procedure btnFirstClick(Sender: TObject);
    procedure btnNewClick(Sender: TObject);
    procedure btnNextClick(Sender: TObject);
    procedure btnTestClick(Sender: TObject);
  private
    { private declarations }
    conn : TMySQL50Connection;
    query : TSQLQuery;
    transaction : TSQLTransaction;
    procedure Display;
  public
    { public declarations }
  end;
var
  Form1: TForm1;
implementation
{ TForm1 }
procedure TForm1.btnTestClick(Sender: TObject);
var
  S: String;
begin
  conn := TMySQL50Connection.Create(nil);
  query := TSQLQuery.Create(nil);
  transaction := TSQLTransaction.Create(nil);
  try
    try
      // Adjust to your own database server, username and password:
      conn.HostName := '127.0.0.1';
      conn.UserName := 'root';
      conn.Password := '';
      // If you use a different database name, adjust here:
      conn.DatabaseName := 'test1';
      conn.Connected := True;
      conn.Transaction := transaction;
      query.DataBase := conn;
      //query.ParseSQL := true; //line not needed - this is the default anyway
      //query.ReadOnly := false; //line not needed - this is the default anyway
      query.SQL.Text := 'select * from tperson';
      query.Open;

      query.Last;
      S := IntToStr(query.RecordCount) + #13#10;
      query.First;

      while not query.EOF do
      begin
        S := S + query.FieldByName('surname').AsString + #13#10;
        query.Next;
      end;
    finally
      //query.Free;
      //conn.Free;
    end;
  except
    on E: Exception do
      ShowMessage(E.message);
  end;
  Memo1.Text:= S;
end;

procedure TForm1.Display;
begin
  edtPersonID.Text := query.FieldByName('personid').AsString;
  edtSurname.Text := query.FieldByName('surname').AsString;
  edtDOB.Text := query.FieldByName('dob').AsString;
end;

procedure TForm1.btnFirstClick(Sender: TObject);
begin
  query.First;
  Display;
end;

procedure TForm1.btnNewClick(Sender: TObject);
begin
  query.Append;
  query.FieldValues['personid'] := edtPersonID.Text;
  query.FieldValues['surname'] := edtSurname.Text;
  query.FieldValues['dob'] := edtDOB.Text;
  query.Post;  
  query.ApplyUpdates; //to apply update
  transaction.Commit; //Needed since FPC 2.6.4; todo: somebody should check if this is enough
end;

procedure TForm1.btnNextClick(Sender: TObject);
begin
  query.Next;
  Display;
end;

initialization
  {$I unt_db.lrs}
end.

RAD/Databound controls

Please see SQLdb_Tutorial1, SQLdb_Tutorial2 and further tutorials.

Zeos

See ZeosDBO

Pascal Data Objects (PDO)

Pascal Data Objects is an alternative data access layer that seems to support:

  • MySQL 4.0 clients
  • MySQL 4.1 clients
  • MySQL 5.0 clients
  • (and also) Firebird 1.5 and 2.0

Functions introduced with MySQL 4.1 and 5.0 like prepared statements, binding, and stored procedures are supported. PDO is inspired by PHP Data Objects. All the code and documentation necessary to use this API is available on sourceforge:

[1]

MySQL package: the low level units

As with all databases, the SQLDB code depends on a lower level mysql specific unit that wraps around the mysql driver library (.so/.dll). Normally, you would use the higher-level SQLDB code as it allows you to code more quickly, easily switch databases etc.

Using this is very easy, all you need to do is compile some units, and use these units in your program. You need to specify the location in the filesystem of the MySQL client Library (libmysqlclient on Linux) when compiling, and that is it.

Provided units and programs

The packages provides 3 units, of which normally only the first is needed:

  • mysql the main mysql unit.
  • mysql<version> (e.g. mysql50) provides access to the specific mysql library for that version. Note: the client library version is unrelated to the version of the server in use - except that you want to make sure these versions are compatible.
  • mysql<version>com contains some internal routines of MySQL (presumably a translation of mysql_com.h); it should normally not be used unless you want access to some internal types.

Example programs can be found in the <fpc>\packages\mysql\examples directory.

Installation

The mysql interface is distributed with the Free Pascal packages, and come with the compiler distribution: Normally no action should be taken to work with MySQL.

In case you want to modify and compile the units yourself, the mysql sources are in the packages directory: packages/mysql

This directory contains the units, a test program and a makefile. cd to the directory and type

make

This should compile the units. If compilation was succesful, you can install with

make install

You can then test the program by running

make test

This will:

  • Run a script to create a table in a database, and fill it with some data. (the mysql program should be in your PATH for this) . By default, the used database is testdb.
  • Run the testprogram testdb
  • Run a shell script again to remove the created table.

You will see a lot of messages on your screen, giving you feedback and results. If something went wrong, make will inform you of this.

Go back to Packages List

See also