Delphi Database Programming with MySQL - Creating a phone book application
Part I - Getting ready
- Introduction
- Setting up MySQL
- Setting MicroOLAP DAC for MySQL component
Part II - Let's get started
- Delphi and DAC for MySQL database components
- Designing the Delphi forms
- More features of microOLAP's DAC for MySQL
Part III - The end
- Final words
- Acknowledgement
- References and links
Part I - Getting ready
In this artcile you will learn how to create database programs using Delphi
and MySQL. You are required to have basic Delphi and SQL programming skills
only. In the next section we will get to installing MySQL and download the MySQL
DAC Components. By the end of this article you will have learned how to write
your own database programs using Delphi and MySQL.
MySQL is a free DBMS and can be downloaded from MySQL.com website. You need
to get the Windows version for this article.
After downloading it, you need to set it up, select the administrator password.
Second thing to be done is to create the database and the needed tables.
- Start -> Programs -> MySQL -> Start Command Line MySQL Client
- You need to enter the password that you used during the setup phase
- Create a new database named "phonebook":
create database phonebook;
- Select that database:
use phonebook;
- And finally create the table we are going to use:
CREATE TABLE contacts (id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR (200),
email VARCHAR (200),
phone VARCHAR (50),
comments TEXT,
picture MEDIUMBLOB,
PRIMARY KEY(id));
Notice that we created an ID as a primary key, basic text fields for the name/address/email/etc...
and a blob field to store the contact's picture.
- If all was okay then you should see no errors and your screen would like
something like this:
1. 3 - Setting microOLAP DAC for MySQL component
There are more than a way to use MySQL from inside Delphi, some of these ways
are:
- Port the MySQL C header files into Delphi and use LibMySql.dll
- Use MySQL's ODBC drivers and then use Delphi's ADO components
- Use a third party component that makes accessing MySQL the least of your
worries
The first method is not really feasible and makes your programming hard, especially
if you are going to make use of data aware components. The second method is
acceptable but it requires many prerequisits on the client's machine and may
or may not exploit the full features of MySQL. We are going to explore the 3rd
solution using microOLAP's excellent MySQL component called DAC for MySQL (Direct
Access Component).
Before proceeding, please download and install the component from: http://www.microolap.com/products/connectivity/mysqldac/
From the microOLAP website, here are ten top reasons to use the DAC component:
- licensed per a developer without royalty fee: you don't need to purchase
end-user run-time licenses at all;
- no MySQL libraries (libmysql.dll) are required on a client workstation;
- 100% native Delphi code;
- support of Delphi 5-7, C++Builder 5-6, Borland Developer Studio 2005-2006
Win32 edition, Turbo Delphi 2006, Turbo C++ 2006, CodeGear RAD Studio 2007
(Delphi 2007) Win32 Edition and MySQL 3.xx/4.x/5.x;
- only 300-400 Kb are added to your .exe file;
- full support of stored procedures (with IN, OUT and INOUT parameters);
- full compatibility with all the existing data-aware controls and report
designers;
- full support of the BLOB fields;
- TDBImageEx component for JPEG images support included in the package
for free (with sources);
- TNT
Unicode Controls Wrappers package for Unicode applications for free
(with sources);
- detailed help system and a lot of various demo applications;
- and much more. Please find more details in the online
documentation.
Now that you have everything ready, let us get started!
Part II - Let's get started
Before introducing the components, let me make sure that you are aware of the
following concepts needed to access databases from Delphi:
- A database connection: This mechanism allows us to define a server / database.
In that way we know with whom we can talk and communicate
- A table object: This is a logical represenation of a database tabe. It allows
us to list rows within a table, insert or delete rows.
The table object is usally associated with a database grid component (such
as Delphi's TDBGrid). Such objects are known as data sets. Other data sets
can be a query (which also provides data when the query is executed).
- Datasource: Data sources are the intermediate link between the table objects
and the visual component (such as a dbgrid).
Putting it all together, we first need a database connection and a table object.
Then if we want to represent the table visually, we need to insert a data source
and link it with the table object (dataset), and have the data source linked
to a dbgrid component.
The following screenshot demonstrates what we need:
- We select DAC for MySQL components from this newly installed package
- The MySQL database connection (needs: server name, username/password, and
database name).
- A logical MySQL table representation object (needs: The table name)
- A datasource which has its dataset linked to (3)
- A database string grid which has its datasource linked to (4)
Let us configure the mySQLDatabase1 component together:
- Database address
- username / password
- database name
- and finally set it to Connected (not before)
We will design our application using one form, however all the screens will be inside tab pages. If we use this method we won't have to use a data module unit (which is used to centralize database connection and other objects).
- List all: To list all the items in the database (showing you how to use
a TmySQLTable and a DBGrid)
- Manage: Allows you to create and edit users. Also demonstrates how to load
and store pictures in the MySQL database
- Search: Demonstrates how to build a prepared query and use the TmySQLQuery
component
The "List all" page
For that we need a TmySQLTable component linked to the mySQLDatabase1
and its table name set to "contacts", then we need a data set
linked to the TMySQLTable DataSet and finally a DBGrid linked to the DataSet.
Make sure you set the DataSet active.
Now you may adjust the DBGrid and select the fields you want to have displayed.
To do that, double click on the DBGrid and right-click/Add all fields. After
adding all the fields, you may now edit each field and delete it if you don't
want it displayed.
For example:
Nothing additional is needed to be done in that page. The DBGrid will enumerate
all the elements using DAC's dataset.
The "Manage" page
Let us create Edit Boxes for each of the DB fields. First we need another TmySQLTable,
then we double click on it and we right-click and add all fields. Now that the
fields are selected, we drag and drop them into the form. Automatically Delphi
will create for us appropriate Edit and Memo boxes.
Notice now we have all those controls and they are data-aware, that means whenever
we change them, the changes are reflected on the database.
Now that we want to have a picture for each contact, we are going to drop into
our form a TDBImage control (wuth datafield='picture' and datasource='dsManage').
Then whenever the user double clicks on that control, we will want to show the
"Open Dialog" and insert the picture into the blob.
procedure TForm1.DBImage1DblClick(Sender: TObject);
var
BlobField1: TBlobField;
begin
// allow picture edition only in edit or insert mode!
if not (
(dsManage.State = dsEdit) or (dsManage.State = dsInsert)
)
then
Exit;
BlobField1 := TBLOBField(DBImage1.Field);
BlobField1.Transliterate := false;
if dlgOpen1.Execute then
begin
BlobField1.LoadFromFile(dlgOpen1.FileName);
dsManage.DataSet.Post;
end;
end;
And to finalize and make things simple, we will add a TDBNavigator to the manager
form so that we can easily insert/edit or delete records.
At the end, our manager form will look something like that:
The "Search" page
Now that we have finished most of the tab pages using the excellent help of microOLAP's DAC, we will now show you how to create queries using your code.
We will illustrate how to use DAC's TmySQLQuery and how to setup prepared statements.
Before we begin make sure you insert a new TmySQLQuery named "querySearch"
and set its database value correctly, also insert a TDataSource and bind it with
the search result DBGrid.
Let us take the example of finding by name, the prepared statement should be something
like:
SELECT
name, email, phone
FROM
contacts
WHERE
name = :name
Notice how we use the ":name" which designates a variable to be replaced
when the statement is prepared.
To continue, let us pass this query to the component and pass the name
parameter then execute the statement as:
querySearch.SQL.Text := 'SELECT name, phone, email FROM contacts WHERE name=:name';
querySearch.Params.ParamByName('name').AsString := txtQuery.Text;
querySearch.Open;
lblResults.Caption := Format('%d record(s) found!', [querySearch.RecordCount]);
Now that you know how we can put the parameter of a prepared statement, let
us look on how we can write the search form based on the selection of the user.
The search code could be something like that:
procedure TForm1.Button1Click(Sender: TObject);
begin
if (rbEverything.Checked) then
begin
querySearch.SQL.Text :='SELECT name, phone, email FROM contacts';
end
else if (rbByName.Checked) then
begin
querySearch.SQL.Text := 'SELECT name, phone, email FROM contacts WHERE name=:name';
querySearch.Params.ParamByName('name').AsString := txtQuery.Text;
end
else if rbByEmail.Checked then
begin
querySearch.SQL.Text := 'SELECT name, phone, email FROM contacts WHERE email=:email';
querySearch.Params.ParamByName('email').AsString := txtQuery.Text;
end
else if rbByPhone.Checked then
begin
querySearch.SQL.Text := 'SELECT name, phone, email FROM contacts WHERE phone=:phone';
querySearch.Params.ParamByName('phone').AsString := txtQuery.Text;
end;
querySearch.Open;
lblResults.Caption := Format('%d record(s) found!', [querySearch.RecordCount]);
end;
The article barely demonstrated one of the many facilities provided by microOLAP's DAC.
It is worth mentioning the following additional components:
- TmySQLDump: Allows you to dump a complete set of table into .SQL file. You
may later restore the SQL file using the batch component of DAC or use mysql
command client.
- TmySQLMonitor: Allows you to monitor all SQL commands that are executed
among all the DAC SQL component in your project. This is useful for logging
all the queries to a file and then tracking the errors if any occur during
the early stage of development.
- TMySQLBatchExecute: Excellent component allowing you to execute SQL scripts
containing more than one SQL statement. SQL script text must be set in SQL
property. Each SQL statement must be separated by the symbol set in. Delimiter
property (";" by default). This is very useful to restore a dumped
SQL file back into the database
- TMySQLStoredProc: allows to execute stored procedures in MySQL 5.0+ database.
It supports IN, OUT and INOUT parameters.
Part III - The End
I hope you have found benefits in this introductory article. MySQL is an excellent
DBMS, but using it with Delphi was a hassle, but after finding DAC for MySQL, programming
MySQL was so simple and transparent. Hope you find DAC for MySQL helpful too.
I would like to thank all the people who contributed to the Delphi community through free components, newsgroups contributions, articles and tutorials.
Many thanks to microOLAP for "DAC for MySQL" component which is really simple to use but very powerful.
microOLAP also encourages users to earn free copies of the component through writing a tutorial, I won my copy, so can you! Spread the word.
Download the project files here. Some
websites that can be of help to you:
Home