MySQLDatabases

From Lazarus wiki
Jump to navigationJump to search

Introduction

Work in progress

In the Database tutorial we saw a first attempt to connect to a MySQL server. We did not use any components, either visual or non-visual at that time. This page will explain how to connect to a MySQL server in a (perhaps) easier way.

Components to use

MySQL Components

If you look in the $Lazarus/components/mysql directory you will find two lazarus packages. There is a package for MySQL version 3.2x (mysql3laz.lpk) and one for MySQL version 4.x (mysql4laz.lpk). If you did not do so yet, install the appropriate package, depending on the server version. Remember that it is not possible to use the package for version 3 to connect to a server running version 4 or vice versa. When you've installed this package you will see a new tab in the component palet, called MySQL. On this tab there are two components, TMySQLDatabase and TMySQLDataset.

SQLdb Components

Another possibility is the installation of the package in the $Lazarus/components/sqldb directory. In this directory you see a package file called sqldblaz.lpk. You need to install this package and the mysql4connlaz.lpk form the $Lazarus/components/sqldb/mysql directory. The first package contains some general components used for all databases. These component are TSQLTransation and TSQLQuery and can be found on the new SQLdb tab. After installation of the mysql4connlaz.lpk you will find a third component on the SQLdb tab called TMySQLConnection (depicted by a dolphin).

If you do not know how to install components / packages, have a look at this page for an "Install Howto". As the SQLdb components are the more general and can be used for other databases just by replacing the TMySQLConnection with for instance a TIBConnection, we will develop a program with the SQLdb components.

Our program

The basics

We will try to make a program based on the one made here (in Dutch) which is based on the original (in English) by Chris.

The main form

We will use the same main screen and build all functionality from scratch :) As you will see there is a lot less to take care of, because the components really take away all the hard stuff! So lets start by making a screen that looks like this.
Trymysql.png
From the SQLdb-tab place a TMySQLConnection, a TSQLTransaction and a TSQLQuery Components.png on this form. Don't change the default names given to this components. We have to link these components together so they can do their job. So the following properties have to be set:

Component Property Value
MySQLConnection1 Transaction SQLTransaction1
SQLTransaction1 Database MySQLConnection1
SQLQuery1 Database MySQLConnection1
SQLQuery1 Transaction SQLTransaction1

The Transaction-property of SQLQuery1 will autatically be set if you have set the Transaction property of MySQLConnection1 first. When you set this, you will notice that SQLTransaction1.Database has been set to MySQLConnection1.

The code

As you can see in the screendump 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 diabled. We could decide to disable "Connect to Server" as well untill 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 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('Retreiving 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 itterate through the records be 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;

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.