MySQLDatabases/fr

From Free Pascal wiki
Jump to navigationJump to search

Deutsch (de) English (en) français (fr) 日本語 (ja) polski (pl) slovenčina (sk)

Work in progress

Introduction

Cette page expliquera comment se connecter à un serveur MySQL en utilisant des composants visuels.

Light bulb  Remarque: Cette page a été écrite il y a longtemps et peut être dépassée. Aussi, la plupart des concepts décrits ici ne sont pas spécifiques à MySQL mais s'appliquent à tous les bases de données SQLDB. Donc suivre les tutoriels SQLDB ci-dessous pourrait être plus facile.

En complément des tutoriels listés en bas de cette de page, voir aussi mysql/fr#Tutoriels et exemple de code pour plus de tutoriels qui sont écrits depuis longtemps aussi

Dans Database tutorial nous avons vu une première tentative de connexion à un serveur MySQL. Nous n'avons utilisé aucun composant, qu'il soit visuel ou non-visuel, à ce moment là. Cette page expliquera comment se connecter à un serveur MySQL d'une façon (peut-être) plus facile.

Composants disponibles

Composants SQLdb

Une autre possibilité est l'installation du package su dossier $Lazarus/components/sqldb. Dans ce dossier vous trouverez un package appelé sqldblaz.lpk. Vous devez installer ce package et le mysql4connlaz.lpk du dossier $Lazarus/components/sqldb/mysql. Le premier package contient quelques composants génériques utilisés par toutes les bases de données. Ces composants sont TSQLTransaction et TSQLQuery et peuvent être trouvés dans le nouvel onglet SQLdb. Après installation du mysql4connlaz.lpk vous trouverez un troisième composant sur l'onglet SQLdb appelé TMySQLConnection (représenté par un dauphin).

Si vous ne pouvez pas trouver le dossier $Lazarus/components/sqldb/mysql ni mysql4connlaz.lpk, cela signifie que vous utilisez une version plus récente dans laquelle mysql4connlaz.lpk est incluse danssqldblaz.lpk. C'est Ok, si vous installez sqldblaz.lpk, vous aurez tous els composants mentionnés dans le même onglet de l'IDE.

Si vous ne savez pas comment installer des composants/packages, jetez un oeil à ceci page pour un "Install Howto".

Etant donné que les composants SQLdb son,t bien plus génériques et qu'ils peuvent être utilisés avec d'autres bases de données en remplaçant simplement la TMySQLConnection avec par exempke une TIBConnection, nous développerons un programme avec les composants SQLdb.

Explication des composants utilisés

TMySQLConnection

TMySQLConnection est utilisé pour stocker des paramètres pour se connecter au serveur de base de données. Il vous permet de configurer l'hôte auquel vous vous connectez ainsi que l'userid et le password à utiliser dans la connexion. Une autre propriété de TMySQLConnection est utilisée pour indiquer la base de données que vous voulez utiliser. Le 'LoginPrompt' n'est pas encore fonctionnel, donc assurez-vous qu'à côté des HostName et DatabaseName les propriétés UserName et Password soient bien renseignées avant de tenter d'ouvrir une connexion.

Assurez-vous d'utiliser TSQLTransaction dans votre MySQLConnection en renseignant la propriété Transaction ou bien vous n'aurez pas la possibilité d'ouvrir une SQLQuery.

Note. Dans les dernières versions SVN de Lazarus vous trouverez 3 composants MySQLConnection. Il y a TMySQL40Connection, TMySQL41Connection et TMySQL50Connection. Assurez-vous d'utiliser la version correcte correspondant à votre serveur. Donc si vous utilisez un MySQL 4.1 utilisez un TMySQL41Connection.

TSQLTransaction

Une SQLTransaction est nécessaire pour certains travaux internes. Une SQLTransaction est automatiquement avtivée quand vous ouvrez un dataset l'utilisant. En fermant une connexion désactive également la transaction associée et ferme tous les datasets l'utilisant.

TSQLQuery

TSQLQuery est utilisé pour exécuter les commandes SQL sur le serveur. Vous pouvez récupérer des données en positionnant le SQL à quelque commande SELECT et en l'appelant avec la méthode Open. Ou vous pouvez manipuler les données en faisant des INSERT, DELETE or UPDATE. Dans le dernier cas, vous ne devez pas utiliser la méthode Open mais la méthode Execute.

TDataSource

Un DataSource met à disposition la connexion entre les composants 'data aware' visibles comme DBEdit, DBGrid et un dataset. Il permet aux données d'être disponibles pour l'affichage par les composants 'data aware'. Une datasource ne peut être connectée qu'à un seul dataset à la fois mais il peut y avoir plusieurs composants 'data aware' connectés dessus.

TDBGrid

Un DBGrid peut être utilisé pour présenter les données récupérées par un Dataset. Le DBGrid a besoin d'une datasource pour se connecter à un dataset. Quand le dataset est ouvert, le DBgrid sera automatiquement peuplé avec les données.

Notre programme

Les bases

Nous essaierons de réaliser un programme basé sur celui here (in Dutch) qui est basé sur original (in English) par Chris.

La fiche principale

Nous utiliserons le même écran principal et construirons toutes les fonctionnalités à partir de rien :) Comme vous le verrez il y a ici beaucoup de choses en moins à prendre en compte, parce que les composants nous débarrassent réellement du plus gros du travail! Donc commençons par faire un écran qui ressemble à ceci.
Trymysql.png
Depuis l'onglet SQLdb-tab plaçons un TMySQLConnection, un TSQLTransaction et un TSQLQuery Components.png sur cette fiche. Ne changez pas les noms par défaut donnés à ces composants. Sauf pour le composant Connection. Pour que cet article puisse s'appliquer à toutes les versions de MySQL, renommez votre MySQL??Connection composant: MySQLConnection1 Nous avons à lier ces composants ensemble pour qu'ils puissent faire leur travail. Dons les proporiétés suivantes ont à être configurées:

Composant Propriété Valeur
MySQLConnection1 Transaction SQLTransaction1
SQLTransaction1 Database MySQLConnection1
SQLQuery1 Database MySQLConnection1
SQLQuery1 Transaction SQLTransaction1

La propriété Transaction de SQLQuery1 sera automatiquement configurée si vous avez configuré la propriété Transaction de MySQLConnection1 en premier. Quand vous aurez configuré ceci, vous noterez que SQLTransaction1.Database a pour valeur MySQLConnection1.

Comme dit plus tôt: Assurez-vous que vous utilisez le composant Connection correct pour la version de votre serveur MySQL.

The code

As you can see in the screen dump the only buttons available on start of the program are "Connect to server" and "Exit". For the other buttons to work we need more information so these are disabled. We could decide to disable "Connect to Server" as well until the information for the host, username and password has been given. I decided against this because our user might think: "Nothing seems possible, so let's hit exit." :)

Before I start giving you any code I would like to stress that there should be more exception handling in the code. Critical sections should be placed in

try ... finally

or

try ... except

constructions.

Connect to a server

The first thing we have to do is get connected to our server. As when connecting we don't know what databases are available on the server we will ask for a list of databases on connecting. However there is one catch, to make the connection we have to enter a valid DatabaseName in the properties of the MySQLConnection. You will see in the code that I am using the "mysql" database. This database is used by mysql for some housekeeping so it will always be there.

procedure TFormTryMySQL.ConnectButtonClick(Sender: TObject);
begin
  // Check if we have an active connection. If so, let's close it.
  if MySQLConnection1.Connected then CloseConnection(Sender);
  // Set the connection parameters.
  MySQLConnection1.HostName := HostEdit.Text;
  MySQLConnection1.UserName := UserEdit.Text;
  MySQLConnection1.Password := PasswdEdit.Text;
  MySQLConnection1.DatabaseName := 'mysql'; // MySQL is allways there!
  ShowString('Opening a connection to server: ' + HostEdit.Text);
  MySQLConnection1.Open;
  // First lets get a list of available databases.
  if MySQLConnection1.Connected then begin
    ShowString('Connected to server: ' + HostEdit.Text);
    ShowString('Retrieving list of available databases.');
    SQLQuery1.SQL.Text := 'show databases';
    SQLQuery1.Open;
    while not SQLQuery1.EOF do begin
      DatabaseComboBox.Items.Add(SQLQuery1.Fields[0].AsString);
      SQLQuery1.Next;
    end;
    SQLQuery1.Close;
    ShowString('List of databases received!');
  end;
end;

The first thing we do is check to see if we are connected to a server, if we are then we call a private method "CloseConnection". In this method some more housekeeping is done. like disabling buttons and clearing comboboxes and listboxes. Then we set the necessary parameters to connect to server.

Throughout our program you may see calls to ShowString. This method adds a line to the memo on our form which acts like a kind of log.

With the parameters set, we can connect to the server. This is done by calling

MySQLConnection1.Open;

In a proper application one would place this in an exception handling construct to present a friendly message to the user if the connection failed. When we are connected we want to get a list of databases from the server. To get data from the server a TSQLQuery is used. The SQL property is used to store the SQL-statement send to the server. MySQL knows the "SHOW DATABASES" command to get the list of databases. So after we have set the SQL-text, we call

SQLQuery1.Open;

The result set of a SQLQuery can be examined through the fields property. As you can see we iterate through the records by calling

SQLQuery1.Next;

When we have added all available databases to our combobox, we close the SQLQuery again.

Selecting a database

If the user selects a database in the DatabaseComboBox we enable the "Select Database" button. In the OnClick event of this button we set the DatabaseName of MySQLConnection1, and request a list of tables. The last statement of this procedure enables the "Open Query" Button, so the user can enter a query in the "Command" Editbox and have it send to the server.

procedure TFormTryMySQL.SelectDBButtonClick(Sender: TObject);
begin
  // A database has been selected so lets get the tables in it.
  CloseConnection(Sender);
  if DatabaseComboBox.ItemIndex <> -1 then begin
    with DatabaseComboBox do
      MySQLConnection1.DatabaseName := Items[ItemIndex];
    ShowString('Retreiving list of tables');
    SQLQuery1.SQL.Text := 'show tables';
    SQLQuery1.Open;
    while not SQLQuery1.EOF do begin
      TableComboBox.Items.Add(SQLQuery1.Fields[0].AsString);
      SQLQuery1.Next;
    end;
    SQLQuery1.Close;
    ShowString('List of tables received');
  end;
  OpenQueryButton.Enabled := True;
end;

MySQL has a special command to get a list of tables, comparable to getting the list of databases, "show tables". The result of this query is handled in the same way as the list of databases and all the tables are added to the TableComboBox. You might wonder why we do not open the connection again before opening the query? Well, this is done automatically (if necessary) when we activate the SQLQuery.

Fields in a table

In MySQL you can again use a form of "SHOW" to get the fields in a table. In this case "SHOW COLUMNS FROM <tablename>". If the user picks a table from the TableComboBox the OnChangeEvent of this ComboBox is triggered which fills the FieldListbox.

procedure TFormTryMySQL.TableComboBoxChange(Sender: TObject);
begin
  FieldListBox.Clear;
  SQLQuery1.SQL.Text := 'show columns from ' + TableComboBox.Text;
  SQLQuery1.Open;
  while not SQLQuery1.EOF do begin
    FieldListBox.Items.Add(SQLQuery1.Fields[0].AsString);
    SQLQuery1.Next;
  end;
  SQLQuery1.Close;
end;

As well as the names of the fields, the result set contains information on the type of field, if the field is a key, if nulls are allowed and some more.

Showing the data

Well as we said we would use components to get connected to the database, lets use some components to show the data as well. We will use a second form to show a grid with the data requested by the user. This form will be shown when the user typed a SQL command in the "Command" editbox and afterwards clicks the "Open Query" button. This is the OnClick event:

procedure TFormTryMySQL.OpenQueryButtonClick(Sender: TObject);
begin
  ShowQueryForm := TShowQueryForm.Create(self);
  ShowQueryForm.Datasource1.DataSet := SQLQuery1;
  SQLQuery1.SQL.Text := CommandEdit.Text;
  SQLQuery1.Open;
  ShowQueryForm.ShowModal;
  ShowQueryForm.Free;
  SQLQuery1.Close;
end;

The ShowQueryForm looks like this:

Mysqlshow.png

and contains a

TPanel Align alBottom
TDataSource
TDBGrid Align alClient
DataSource DataSource1
TButton Caption Close

The button is placed on the panel. What happens in the "Open Query" OnClick is this. First we create an instance of TShowQueryForm. Secondly we set the DataSet property of the DataSource to our SQLQuery1. Then we set the SQLQuery SQL command to what the user entered in the "Command" editbox and open it. Then the ShowQueryForm is shown modally, this means that it will have the focus of our application until it is closed. When it is closed, we "free" it and close SQLQuery1 again.

Sources

The sources for this project can be downloaded here For more demo projects see sourceforge