Sie sind auf Seite 1von 36

qwertyuiopasdfghjklzxcvbnmqw

ertyuiopasdfghjklzxcvbnmqwert
yuiopasdfghjklzxcvbnmqwertyui
opasdfghjklzxcvbnmqwertyuiopa
Delphi Database Application
Development
sdfghjklzxcvbnmqwertyuiopasdf
Using MySQL

ghjklzxcvbnmqwertyuiopasdfghj
8/2/2018

Larry Vincent Regencia

klzxcvbnmqwertyuiopasdfghjklz
xcvbnmqwertyuiopasdfghjklzxcv
bnmqwertyuiopasdfghjklzxcvbn
mqwertyuiopasdfghjklzxcvbnmq
wertyuiopasdfghjklzxcvbnmqwe
rtyuiopasdfghjklzxcvbnmqwerty
uiopasdfghjklzxcvbnmqwertyuio
pasdfghjklzxcvbnmqwertyuiopas
dfghjklzxcvbnmqwertyuiopasdfg
Contents
DELPHI APPLICATION PROGRAMMING GUIDE ......................................................................................... 2
Managing your Delphi Projects ................................................................................................................. 2
Starting your first Delphi Project .............................................................................................................. 3
First Delphi Project.................................................................................................................................... 5
Using the MainMenu Control ................................................................................................................... 6
Adding New Forms in the Project ............................................................................................................. 8
Using Components in the Form .............................................................................................................. 12
Establishing the Database Connection ................................................................................................... 14
Inserting New Records to the Database ................................................................................................. 20
UPDATING RECORD................................................................................................................................. 25
DELETING RECORDS ................................................................................................................................ 28
Populating data in a combo box ......................................................................................................... 30
Saving and Storing Dates from a DateTimePicker .............................................................................. 32
Computing your Age ........................................................................................................................... 33
DELPHI APPLICATION PROGRAMMING GUIDE
Version 1.2

Managing your Delphi Projects

In short, a Delphi project is just a collection of files that make up an application


created by Delphi. DPR is the file extension used for the Delphi Project file format to
store all the files related to the project. This includes other Delphi file types like
Form files (DFMs) and Unit Source files (.PASs).

You can also get more information with regards to understanding Delphi Project
here: https://www.thoughtco.com/understanding-delphi-project-files-dpr-1057652

To understand more on Delphi file types, you can visit this link:
https://www.thoughtco.com/filename-extensions-in-delphi-1057643

Always take into consideration the following:

1) Save all project files (.dpr, .pas, .dfms) in one folder.


2) Once you start a project, always SAVE the file(s) and ALWAYS follow a
naming convention and make sure to use descriptive filenames to avoid
confusion.
3) Form names MUST NOT be the same as file names. For example, if your
project you have form name: frmMainform. DO NOT use the same filename
when saving the form. You can probably do a reverse of the filename or omit
the ‘frm’ prefix.
4) You can save forms in subfolders within your main project folder.

Starting your first Delphi Project

Be familiar with the Delphi Integrated Development Environment (IDE).

- Menu Bar
- Object Inspector
- Controls / Objects tabs
- Unit / Form

The above lists are the most basic part of the Delphi IDE that you need to be familiar
with.
This is the Delphi form. To switch to and from the Design View of the form & the
Code View of the form, press F12.

This is the code underlying your form.


Before you proceed any further, it is a good practice to SAVE your project first under
a one folder.

.pas – These files refers to your Forms. Always use filenames are descriptive enough
as to what the form is for.

.dpr – This file is your Project file. The project file allows you to organize your forms
and other project files properly. It is also the file that will allow you to run your
project. If you do not have this file open, you cannot Run your project or forms.

Filenames should not contain spaces.

The location of your project files if you are using default location should be in this
folder: C:\Program Files (x86)\Borland\Delphi7\Projects or
D:\Program Files (x86)\Borland\Delphi7\Projects or you can always save
them under your preferred folders.

Once you have save your Project files, you can now start working on the forms.

Always take note of the naming convention for Forms and Objects. The primary
objective of this naming convention really is to avoid confusion and save time
navigating throughout your project.

When naming forms and objects please observe the following prefixes:

frm – Forms cmb – Combo Box DM – datamodule


edt – Editbox lst – List Box Qry-query datasets
lbl – Label btn – Buttons
Ex: frmMain, edtFirstname, cmb_gender, lst_Category, DM, qrySelect, qryInsert
lblResult btnSearch
There are so many objects in Delphi, you can come up your own prefix not listed
above, just make sure you know which component you are referring to.

First Delphi Project


1) When you open Delphi 7, it will automatically open with a default project,
with one form already opened. Save the project as SampleData, go to File
Save Project As… then save the also form as frmMain.
Saving the form in the folder. (.pas file extension)

2) Be familiar with the IDE, click on Form1 and go to the Object Inspector on
the lower left of the screen.
Object Inspector – allows you to make changes to a form or any object
(component) during design time.
3) Rename the Name property of Form1 to frmMain. Naming your forms makes
it easier to find and navigate once the projects gets bigger.
4) After changing the Name property of the form, it will also change the
Caption property of the form. You can change this to a more appropriate
text.
5) Change additional properties of the form:
Color - $00987E27
Caption – Main Menu
6) Save your work.
7) Press F9 to run the program. You have now created a simplest application in
Delphi.

Using the MainMenu Control


1. In continuation from the previous instructions, add a MainMenu control to
the form. Go to StandardMainMenu. Click or double-click to add the control
to the form.
Adding the MainMenu control to the form
2. Double-click on the MainMenu icon. The screen below allows you to create a
simple menu bar.

3. On the blue area, type the name of your command menu. Type Maintenance.
4. Under Maintenance, type Customers. Then add 3 more, Employees,
Suppliers, Products.
5. When you run your project, you will now see a menu bar on the top portion of
your form. Press F9 to run.

Adding New Forms in the Project


1) Now that you have a menu created, let’s add an individual form that will
correspond to every maintenance menu created. We will add 4 forms.
2) Go to FileNewForm. Immediately save every form added to the project to
avoid confusion and name the forms properly. Apply the following form
filename and properties.
Form
Property
- Filename Customerform Employeeform Supplierform Productsform
- Form Name frmCustomers frmEmployees frmSuppliers frmProducts
- Caption Customer List Employee List Supplier List Product List

3) Click on the MainMenu and press F11. It should shift the focus to the Object
Inspector.

4) In the Object Inspector there are two tabs, Properties and Events. Click on the
Events and double-click on the right side of the OnClick event.

5) At this point, we will let our program do something when we click on the
Customers menu. We will display the Customer List form.
6) As you double-click on the OnClick event, you should see the following
procedure in the code underneath it. Every procedure in Delphi has the name
structure. DO NOT delete any part of the highlighted area of the code in order
to avoid unnecessary errors.
7) Take note that in every procedure, there will always be a matching ‘begin’
and ‘end’. In between this area, is the area where you can write or
insert your own code.
8) If ever you will not write any code here, just leave it as is. Delphi will
automatically remove it for you.
9) So now, to display the Customer form, type the following inside the Begin and
End structure.

procedure TfrmMain.Customers1Click(Sender: TObject);


begin
frmCustomers.Showmodal;
end;

10)When you type the frmCustomers.Showmodal, you are calling the Customers
form to be shown. But when you run the application now, it will cause some
error as shown in the screen figure.
11) This is error is due to inability for the Mainform to link to the Customer. It
short, Mainform needs to establish the connection first with the Customer
form so that they can ‘talk’ to each other.
12) Try running your project by pressing F9. For the first time you try to link or
display a form, the linkage here will be done by Delphi itself.

13) When you see this screen, just click Yes. Then run the application again. If the
program runs with no errors, try going to MaintenanceCustomers. The
Customers form should now be displayed.
14) Repeat the same process for Employees, Suppliers and Products in order to
display the other forms. You should now have 4 forms.
Using Components in the Form
The Delphi IDE is a Pascal based programming language but has implemented the
Object-oriented programming capability of the language. Therefore, the interactions
between objects (forms and components) are native to this programming
environment, in fact most modern programming languages have the same capablity
of.

We will now implement some capabilities to our form in the frmCustomers.

1) Go to the Customers form and drop a Panel component (Standard tab then
look for Panel). Panels are not really required here but it makes the layout
much easier to arrange.
2) We need 3 panels in the form. You can do a Copy and Paste of the first Panel.
Panel Properties:
Caption – leave the caption blank
Color - $00987E27
Panel 1 – set Align property to alTop
Panel2 – set Align property to alBottom
Panel3 - set Align property to alLeft

Arrange the panels similar to this one:

3) Drop a DBGrid on the blank area. DBGrid can be found under the Data
Controls tab.
DBGrid – set Align property to alClient

4) Add a Button on the lower right of the form. When adding buttons, it is best to
change the name to make it easier to find.
Button Properties:
Name – btnClose
Caption – Close

Double-click the button and add 1 line of code:

Close; //this command will close the form


procedure TfrmCustomers.btnCloseClick(Sender: TObject);
begin
Close;
end;
5) Press F9 to test your program.

Establishing the Database Connection


Before we start displaying data on the grid, we need to establish a database
connection. The following are needed:

a) MySQL Database Server running in your computer with the Northwind


Database on it - you can refer to MySQL Installation Guide.
b) MyDAC Component – this is a data access component in Delphi to access
MySQL databases. This is how it looks when installed in Delphi.

Adding the Datamodule

1) In order for us to interact with a database system, our application needs to


establish connection to a database server. In this case, Delphi application and
MySQL.
2) Since we need to connect to the database server regularly, we will create a
single connection for the entire application and place this in a Datamodule.
3) Datamodule are like data components container that allows connection and
datasets to be centrally located in the Delphi project.
4) To add the datamodule, go to FileNewDatamodule. Save it as Datamodule
and change the Name property: DM
We use DM here since we will be referring to this on a regular basis, we don’t
want to type the full Datamodule name.
5) We need to add the MyConnection and MyQuery (dataset) component from
MyDAC.

Property Original Name Change to


Name MyConnection1 Conn
MyQuery1 QrySelect
MyQuery2 QryInsert
MyQuery3 QryUpdateDelete

Connection Component
Conn – will be our connection setting. All datasets will need a connection and
they are refer to this. Properties to be set:
Username: root
Password: admin123
Server: localhost
Once you have supplied all the three, you need to set the following:
LoginPrompt: Disabled
Connected: True
If you are now connected, set the Database to ‘northwind’
At this point, the application is now able to establish a successful connection
to the database server.

Dataset Component
Dataset components are the carrier of our SQL commands. They are one who
will be sending our commands to the database server and holds also the
returned data.
We can add multiple datasets depending on your needs. For now we will need
3, but these datasets can always be reuse across the application or forms.

Properties to be set:
Connection: Conn (apply to all datasets)
Other properties that will be set during runtime are the following: Active, SQL
Text

Displaying the Data on the Grid

1) Go to the Customer form. Add a data source component in the form.

Click on the MyDataSource icon and drop it to the form.


2) Change the Name property: MyDS
If you notice, MyDS has a property called Dataset. This dataset refers to the
dataset created under the Datamodule. Therefore, we need to link our form to
the Datamodule. To do so, go to FileUse Unit… then select Datamodule.
3) In order to establish the link from our DBGrid to the Database Server, you
need to perform the following:
a. Set the DBGrid Property Datasource = MyDS
b. Set MyDS Property Dataset = DM.QrySelect

Right now, our grid does not display anything yet since it did not query
anything.
4) Let the data be displayed when the application is running and the Customer
form is open. So how are we going to do this? Just continue below.

Using Form Events to Activate Database Queries

In this Project, displaying of data on the grid will only be activated when the form is
being opened. Let’s get started.

1) In the Customer form, go to the Object InspectorEvents tab. As you notice,


when you click on the Customer form and go to the Object Inspector, the form
object is not selected. You have to click on the dropdown and select
frmCustomers to display the form properties.
Why is this happening? The reason for this is that, in your Customer form, all
areas of the form are occupied by the panels we added and we cannot click
directly on the form itself. So we have to select it manually from the Object
Inspector
Make sure the form is selected
2) In the Form Events tab, look for the OnShow event. .

3) Double-click on the right side of the OnShow event and add the following
codes. Always make sure to place these codes between the ‘begin’ and ‘end’
keywords. Only encode the highlighted code.
The code highlighted is somehow shortened a little bit due to the ‘with…do’
statements. The equivalent codes for each line are the following:

DM.QrySelect.Active := false;
DM.QrySelect.SQL.Clear;
DM.QrySelect.SQL.Text := ‘SELECT * FROM Customers’;
DM.QrySelect.Active := true;

So what is happening in the code above?

DM.QrySelect.Active := false; - Datasets are usually or can be reused in


Delphi therefore, it is important to deactivate first the dataset before making
any changes

DM.QrySelect.SQL.Clear; - Since datasets contains previous SQL statements


assigned to it, we need to clear them to avoid duplication of commands being
sent to the DB server.

DM.QrySelect.SQL.Text := ‘SELECT * FROM Customers’;


- in this command, we are assigning the dataset with the required SQL
statement that is needed by the user. In this case, the user is requesting to
display all customers.

DM.QrySelect.Active := true; - Once the SQL statement is assigned, we now


activate the dataset in order for it to send such request to the database
server. The database server will then respond with the corresponding
results.

Remember, in the earlier text you assigned a Dataset to the Datasource


(MyDS) and set the Datasource property of the DBGrid to MyDS? That linkage
allows the grid to display whatever data being return by the dataset coming
from the database server.
4) DBGrid Properties to change:
OptionsdgRowselect = True

This property allows the entire row to be selected in the DBGrid.

5) Press F9 to test your program. The screen below should be displayed.

NOTE: I remove the left panel in the form and added the new buttons below.

6) You are now able to display all the Customers in your grid. Now, the challenge
is to apply the same to other forms.
Inserting New Records to the Database
So up next is to be able to perform the corresponding menu: Add, Edit and Delete

ADDING/INSERT NEW RECORD

1) To start with add a new form, go to FileNewForm. Resize the form accordingly, rename the
form to frmCustomerAdd and save it as CustomerAddForm.
2) Properties you can modify in a form during design time:
a. Caption – displayed at the top of the form. Use something descriptive text like ‘Add New
Record’
b. Color – you can always set the form color here whichever you like.
c. Position – position of the form during formshow. Best to set to poDesktopCenter but
feel free to try the other options
d. BorderStyle – allows you to resize forms during runtime. If ever you don’t like that your
form be resize during runtime, change this property to Single.
e. BorderIcons – if you want to disable the minimize, maximize buttons this is the property
you can change. Set biMinimize – False, biMaximize – False then your forms would
disable the minimize and maximize icons on the top right of the form.
3) Add the following labels, editboxes and buttons as shown below.

Name of edit boxes: edtCustomerID, edtCompany, edtFirstname, edtLastname


Name of buttons: btnSave, btnClear and btnClose
4) Go back to the Customer List form. Don’t worry if there’s no data displayed on the grid.
5) When we click the ‘Add’ button (btnAdd), it should display the frmCustomerAdd form. But
before we can write the code it is best to link the forms first. Remember the ‘Use Unit’
function?. So while you are in the Customer List form, go to FileUse Unit.. and select
CustomerAddform and click OK.
6) Now the forms are link. But how will you know they are link? Easy. Simple go to your code by
pressing F12 and you will see that this line (top part) has added CustomerAddForm after the
Datamodule.
7) We now write code in the add button. So when we click on Add, it should display the
frmCustomerAdd. Double-click on btnAdd and type the following:
frmCustomerAdd.showmodal;
8) Now when adding records, we make sure that when the frmCustomerAdd form shows up, the
editboxes should all be empty. So we must clear all the editboxes during the FormShow event.
Go to frmCustomerAdd and go to FormShow event. Add the highlighted code.

9) When frmCustomerAdd shows, the user enters value to the editboxes and the clicks the Save
button. Under the Save button, we write the code for saving new record.
Take note that in our table design, our Customer ID field is set as autonumber, therefore, we
don’t need to specify this value ourselves. And just to make sure Customer ID will not be
modified, set the ReadyOnly property of edtCustomerID to True.
10) In the Save button, we must consider that we are adding a record. But we have to inform the
application that we are adding a record because we will be using the same form for updating
records as well. It should be able to distinguish whether it’s saving a New Record or saving
Changes for an Updated Record. There are a lot of ways to do this but the simplest will be the
form caption. Upon clicking the Add or Update button in the Customer List form, we set the
caption to ‘Add New Record’ or ‘Update a Record’.
11) How to we implement this? Just go back to the Customer List form and double-click on the ‘Add’
button. And add the following code:
frmCustomerAdd.Caption := ‘Add New Record’;
frmCustomerAdd.showmodal;

Are we doing the same for the update? Technically yes but updating record has additional codes
since we need to transfer the selected record to be updated from the grid to the editboxes in
the frmCustomerAdd form.
12) Now we write the code for saving the new record in the frmCustomerAdd form. Double-click on
Save button. Take note that we need to know that we are saving a record and not updating. So
we do need to check the form caption first before we insert a record. Since we will be inserting a
record this means we need to use a DataSet and access our Datamodule. So we also link our
frmCustomerAdd to the Datamodule. So just go to Use Unit and select Datamodule. You can
follow the code below:

if self.Caption = 'Add New Record' then


begin
//validation of inputs, assume here that all 3 fields are required
// and we don't accept blank or empty editbox
if (trim(edtFirstname.Text) = '') or (trim(edtLastname.Text) = '') or
(trim(edtCompany.Text) = '') then
begin
MessageDlg('Please provide data in all fields!', mtWarning, [mbOk], 0);
//Showmessage('I told you no empty editboxes!');
end
else
begin
//Insert Query
with DM.QryInsert do
begin
active := false;
sql.Clear;
sql.Text := 'INSERT INTO customers (company, last_name, first_name) VALUES ('
+ quotedstr(edtCompany.Text) + ','
+ quotedstr(edtLastname.Text) + ','
+ quotedstr(edtFirstname.Text) + ')';
execute;
end;

//Showmessage('Record successfully added!');


MessageDlg('Record successfully added!', mtInformation, [mbOk], 0);
end;

end

Screenshot of the code

13) After performing the Insert operation, we need to update also the grid in order for us to see if
there are any changes or new records added. We can do a re-query in the Customer List form.
So your button Add will not look like this:
So after the Showmodal event of the form, the compiler will read whatever codes next to it. So
since we use the QrySelect dataset for our grid, we will also use the same to update the grid.

UPDATING RECORD
14) So for the Edit/Update button, the code is somewhat similar except that we need to get the ID
of the record being selected.

Remember that before we can perform any update or delete operation, a record MUST be
selected first. So in this case, we are trying to get the ID of the selected record and store it
temporarily in the Hint property of the form. We will use this again to display the details of the
selected record in the frmCustomerAdd form so that the user can perform his changes to the
record.

Take note that we also change the form caption here to: ‘Update Record’
15) Basically this is the flow of our update process:
a. Select a record (to be done within the Customer List form)
b. Save the ID of the selected record (to be done within the Customer List form)
c. Query the details of the selected record using the ID (to be done during formshow event
of frmCustomerAdd)
d. User make changes in the editboxes and click Save. (under the Save button, there should
be another IF statement to determine if the user is performing an Add or Update)
16) You can follow the following code:
Under the frmCustomerAdd formshow event:

Every time we perform an update, this is where we populate the details of the record we want
to update. After we clear the editboxes, we display the individual values for each field in the
frmCustomerAdd form.

In the Save button:


These are the screenshot of the code under the Save button. The first IF statement, performs
the insert and the second IF performs the update.
17) Now your program should be able to perform an insert and update of records.
DELETING RECORDS
18) In deleting records, we will do a simplified process here. The user selects are record from the
Customer List and press Delete button. User is asked for a delete confirmation and once he click
‘Yes’, the record is deleted.
19) This is the code under the Delete button.

The first IF statement there will try to check if the user has selected a record or not. Remember
that in deleting records, we need to select the record first.

The Try…Except statements there allows the application to catch any other errors, this avoid the
application to crash.

Other components that you can implement in your code. I will illustrate here some of the components
that you can use in the program and some important component properties that you need to implement
as well.

DBGrid

DBGrid Properties that needs to be enabled or implemented:


DataSource – make sure your DBGrid must be assigned to a Datasource and your Datasource must also
have a corresponding DataSet

Options – enable Rowselect. If you even notice, if don’t enable the row select property of the DBGrid,
the data inside each cell of the DBGrid can be easily modified/change. We should avoid this from
happening and it’s a MUST to enable the RowSelect set to True.

DBGrid columns – this allow you to customize the columns to be listed or shown in the grid. Take into
consideration that you don’t need to display all columns inside your table but only those fields that are
important to the user.
Combo Box

In the application I sent you, I am utilizing the Employee form to illustrate to you the implementation of
Combo box, list box and radio button.

I am reusing the EmployeeForm here for the purposes of this illustration.

Populating data in a combo box


What I will do in this form is that the customer names will be populated in the combo box.
Steps to follow:

1) You query the records you want to be displayed.


2) Clear the combo box
3) Populate the data in the combo box.

The above code illustrates how you can populate a queried data and store in into the combo box.

//populate the list of customers


while dm.QrySelect.Eof <> true do
begin
cmbCustomers.Items.Add(DM.QrySelect.FieldValues['customername']);
dm.QrySelect.Next;
end;

These codes checks if the Dataset(QrySelect) has reach the end of file (eof). If ever the dataset did not
reach the last record yet he adds the record into the combo box 1 at a time.
dm.QrySelect.Next; - this line allows the dataset to move to the next record
Saving and Storing Dates from a DateTimePicker
This illustration is a little bit long but somehow it makes it easy for you to understand (I hope)!

In this form I added a DatetimePicker, you can check it under the Win32 tab in the components tab.
Then I also add the button. Under the SaveDate button I have the following code. Take note the code
below is now going to work as intended because the Customers table does not have a Birthdate field but
this is show it should be done when storing date and display dates to and from the DateTimePicker.
Computing your Age
Computing your age in Delphi is very easy. There are 2 ways to do this one. Within Delphi or using SQL.

If you want to compute age within Delphi, you can follow this one:

1) Add DateUtils in the ‘uses’ part of your code. This is located at the very beginning of your form
source codes.

2) Add a DateTimePicker in your form, a label where we can display the age and the button for us
to show the computed age.
3) In the button, type the following code:
Label1.Caption := inttostr(yearof(now)-yearof(datetimepicker1.DateTime));

Yearof – this function is part of the DateUtils class. It returns the current year of the selected
date.
4) Run your program and click the button to display the computed age. Very easy! right?
If you want to compute an Age where the data is coming from the Database, you can follow or use the
following:

Assuming we have a Birthdate field in our tbl_student in our Student database. We can simply issue the
query:

SELECT (DATEDIFF(CURRENT_DATE,birthdate)/365) AS Age FROM tbl_student

- CURRENT_DATE here is a MySQL built-in function that returns the current date
- Birthdate is the fieldname

You can issue the above SQL statement to your dataset in Delphi and store the resulting value in a label.
It should look something like this:

with DM.QrySelect do
begin
active := false;
sql.Clear;
sql.Text := SELECT (DATEDIFF(CURRENT_DATE,birthdate)/365) AS Age FROM tbl_student ';
active := true;
end;
Label1.Caption := DM.QrySelect.FieldValues['Age'];

That should do it.

For more MySQL date formatting and functions you can refer here:

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

https://www.w3schools.com/sql/func_mysql_date_format.asp

WORKING WITH SQL


You know already the basic SQL syntax and how to implement them. The challenging part with SQL is
combining multiple tables, functions, groups and other criteria for complex selections. In the previous
lectures I have introduce a SELECT query combining one or more tables using INNER JOIN. This method
I’m going to discuss is a much simple way of implementing multi-table query.
This query combines 4 tables together: Orders, Shippers, Customers and Employees. However, if you
notice it, it didn’t utilize any INNER JOIN keyword. These are called subqueries or sub-Select. These kinds
of queries are ideal of you have multiple foreign keys involved and needs to get additional information
from the parent table of that foreign key.

Example would be, in the Northwind.Orders table you can only see there Customer_ID or Employee_ID.
Now, what if you want to retrieve the firstname and lastname? If look at the 2nd line of the SQL.Text
above, it created a SELECT statement but it compared the primary key of the Customers (id) table and
the foreign key in the Orders (customer_id) table. You see, this has similar results to a query with an
INNER JOIN but subquery are much faster to execute (although it may differ sometimes).

Ask me if you have questions. This is still a work in progress. Typographical errors may be present.

Das könnte Ihnen auch gefallen