0% found this document useful (0 votes)
7 views13 pages

Lesson 3 db

This document provides a detailed lesson on coding in Delphi to manipulate an Access database, specifically focusing on the KSSdb.mdb database and the LearnerTbl table. It covers various coding techniques for basic statistics such as counting records, calculating averages, and searching for records using loops, particularly the While loop. Additionally, it includes instructions for adding, deleting, and updating records within the database using Delphi components and code constructs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views13 pages

Lesson 3 db

This document provides a detailed lesson on coding in Delphi to manipulate an Access database, specifically focusing on the KSSdb.mdb database and the LearnerTbl table. It covers various coding techniques for basic statistics such as counting records, calculating averages, and searching for records using loops, particularly the While loop. Additionally, it includes instructions for adding, deleting, and updating records within the database using Delphi components and code constructs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

KHARWASTAN SECONDARY

GRADE 11 GOOGLE CLASSROOM TERM 2 ACTIVITY


DATABASE AND DELPHI
LESSON 3: CODING IN DELPHI TO MANIPULATE ACCESS DATABASE

PART 1: CODE CONSTRUCT


N.B.
 In this worksheet we will be using the KSSdb.mdb database created in Lesson 1 and the project created in
Lesson 2. The connection from Delphi to the Access database was done already in Lesson 2. You were
instructed not to move the folder from your desktop because of the path of the connection.
 I will teach you how to manipulate the database in various ways using code in Delphi without opening the
database in Access.
 In Lesson 2 you learnt how to automatically view the contents of the table in your database on a DBgrid in
Delphi. There was no code involved there except for the basic setup.
 Manipulating the Database you created in Delphi using code can be done in 2 ways:
o Using Code construct
o Using SQLs (structured query language)
 In this Lesson, I will teach you Code Construct only. SQLs will be visited/taught later on.
 We will be using the folder saved on your desktop in Lesson 1 and Lesson 2 with the connection already
setup.
 Please take note of the following as we proceed with the explanation/tutorial and activity when making
reference to the following from Lesson 1 and Lesson 2:
o Database name KSSdb.mdb
o Table name LearnerTbl
o DataModule names:
 External saves as name KSSdbModule
 Internal name dm
o Also remember that we saved the ADOTable name the same as the table name in the Access
database i.e. LearnerTbl
_______________________________________________________________________________________________
1. EXAMPLES OF MANIPULATING THE DATABASE IN DELPHI:
a. When we are asked to view basic statistics like:
i. Counting records
ii. Highest and lowest values
iii. Sum and average values
iv. Searching for records
v. Etc
b. Other types of manipulation
i. Adding/inserting a new record
ii. Deleting an old record
iii. Updating/editing a record

_______________________________________________________________________________________________
2. CODE CONSTRUCT EXPLANATION FOR BASIC STATICS:
N.B.

There are many different methods/styles to code in Delphi and manipulate the database. However, some code
you may see in textbooks or on the internet may not be accepted.

I will teach you the way I like to code in Delphi with least variation as possible.

1|P ag e “ A I M F O R E X C E L L E N C E ” … E C M
In my attempt below to explain Code Construct, I will be referring to the LearnerTbl below you created in the
KSSdb.mdb database in Lesson 1:

The table in design view: The table in Table view:

a. Let us use the example of counting the number of records in the table without opening the database
in Access.
In order for us to count the records (number of learners), we will have to be able to move from the
first record to the last record and count.

b. Let us use the example of finding the average Fees Owing in the table without opening the database
in Access.
In order for you to find the average Fees Owing, you first need to add up all the Fees Owing of each
record (each learner). This means AGAIN we need to be able to move from the first record to the
last.

c. Let us use the example of searching for a particular record from the table without opening Access.
Usually this is done using the primary key which is the unique key field that identifies each record in
your table. So given an AdminNo of a learner, we need to search through the table to find a match
i.e. we need to be able AGAIN to move from the first record to the last.

Do you remember grade 11 learners doing similar kinds of manipulation in One Dimensional Arrays?
What skill did we use to move from the first position of the array to the last for finding an average
value in the array or finding the highest value in the array?
Yes….You used a loop. You used the FOR loop to move from first subscript value to the last and did all the
manipulation code you needed to do around and inside and after the loop. This was used because you knew
how many values in the array.

In the same way, we need to use a loop to move from first record to the last for basic manipulation and then all
other coding for manipulation can be done before, within and after the loop as you would code using arrays etc.

Because we need to assume we don’t know the number of records in the table in Access when working in Delphi, we
cannot use a For loop. We will therefore be using the While loop for basic manipulation whenever we need to
access every record from the first to the last.
Using:
 your Project created in Lesson 2
 and the DataModule setup with the internal name saved as dm
 and the ADOTable name saved as LearnerTbl,

2|P ag e “ A I M F O R E X C E L L E N C E ” … E C M
We will be using the following ‘FAMOUS 5 LINES’ (the way I like to refer to it as) of code for most questions
involving basic statistic/manipulation:

dm.LearnerTbl.first; //1 …points to first record in the table


while not dm.LearnerTbl.eof do //2 ...runs loop until end of file i.e. till the last record
begin //3 …begin of loop

//body …whatever code is required for manipulation/statistics

dm.LearnerTbl.next; //4 …points to next record


end; //5 …end of while

_______________________________________________________________________________________________
3. CODE CONSTRUCT EXAMPLES FOR BASIC STATICS – ACTIVITY:
a. Open the project you saved and setup in Lesson 2 on your desktop.

b. Currently, the form only has 1 DBgrid which is setup to view records automatically.

c. Add the following components to the form and rename as per instructions below:
i. Tpanel - remove the caption…no need to rename in this example

3|P ag e “ A I M F O R E X C E L L E N C E ” … E C M
ii. Add to the panel the following TButtons and TEdits and 1 TRichEdit – renamed as in
brackets and use Captions as per screenshot below:
1. TButton (btnCount) and TEdit (edtCount)
2. TButton (btnAverageFeesOwing) and TEdit (edtAvg)
3. TButton (btnOldestAge) and TEdit (edtOldestAge)
4. TButton (btnSearch) and TRichedit (redOut)

d. Now let us code the above new components:


***Code btnCount:
i. Code btnCount to count the number of records in the table. Output the result in edtCount.
ii. Code using the ‘FAMOUS 5 LINES’:
procedure TForm1.btnCountClick(Sender: TObject);
var
icount:integer;
begin

icount:=0;

dm.LearnerTbl.First; //1
while not dm.LearnerTbl.eof do //2
begin //3

//body
inc(icount); //the loop takes you through each record and counts it

dm.LearnerTbl.Next; //4
end; //5 end of while

edtCount.Text:= inttostr(icount);

end; //procedure
4|P ag e “ A I M F O R E X C E L L E N C E ” … E C M
iii. Sample run:
Take note when you run the project how the arrow moves from first record to the last.

***Code btnAverageFeesOwing:
i. Code btnAverageFeesOwing to determine the average fees owing in the table.
Output the result in edtAvg.
ii. Code the button using the ‘FAMOUS 5 LINES’:
N.B. In this example we need access to the column with the fees outstanding to add all
amounts together in that column. Whenever we need to reference a specific column in the
table using code we will reference as follows:
In general – the field name is case sensitive and must match the table field name
exactly:
dataModule internal name.table name[‘field name’]
In this example:
dm.LearnerTbl[‘FeesOwing’]

procedure TForm1.btnAverageFeesOwingClick(Sender: TObject);


var
icount:integer;
ravgFees,rTotal:real;
begin

icount:=0;
rTotal:=0;

dm.LearnerTbl.First; //1
while not dm.LearnerTbl.eof do //2
begin //3

//body
inc(icount); //the loop takes you through each record and counts it
rTotal:= rTotal + dm.LearnerTbl['FeesOwing']; //adds all amounts together

dm.LearnerTbl.Next; //4
end; //5 end of while

ravgFees:= rTotal/icount;
edtAvg.Text:= floattostrf(ravgFees,ffCurrency,7,2);

end; //procedure

5|P ag e “ A I M F O R E X C E L L E N C E ” … E C M
iii. Sample run:

***Code btnOldestAge:
i. Code btnOldestAge to determine the oldest age in the table. Output the result in
edtOldestAge.
ii. Code using the ‘FAMOUS 5 LINES’:
Remember in this example you need to reference the Age column in your code.

procedure TForm1.btnOldestAgeClick(Sender: TObject);


var
iOldest:integer;
begin
iOldest:= 0;

dm.LearnerTbl.First; //1
while not dm.LearnerTbl.eof do //2
begin //3

//body
if dm.LearnerTbl['Age'] > iOldest then
begin
iOldest:= dm.LearnerTbl['Age'];
end; //if

dm.LearnerTbl.Next; //4
end; //5 end of while

edtOldestAge.Text:= inttostr(iOldest);
end; //procedure

iii. Sample run:

6|P ag e “ A I M F O R E X C E L L E N C E ” … E C M
***Code btnSearch:
i. Code btnSearch to search for the learner’s details of the admin number entered in by the
user. Output the details found in redOut.
ii. Code using the ‘FAMOUS 5 LINES’:
N.B. We will assume that the AdminNo entered exists therefore only test in your run of
the project with an AdminNo from the existing table.
Also note that again we have to reference a single column to search for the AdminNo
match.
procedure TForm1.btnSearchClick(Sender: TObject);
var
sSearch: string;
begin
sSearch:= edtSearch.Text;

dm.LearnerTbl.First; //1
while not dm.LearnerTbl.eof do //2
begin //3

//body
if sSearch = dm.LearnerTbl['AdminNo'] then
begin
//Type out the richedit lines below as 1 long line. Do not type on separate lines as below!
//the line basically outputs in a neat user-friendly way the details of the searched record.
redout.Lines.Add('Name: '+dm.LearnerTbl['FullName']+#13+ 'GradeDiv: '
+dm.LearnerTbl['GradeDiv']+#13+'Gender: '+dm.LearnerTbl['Gender']+#13+ 'Age: '
+inttostr(dm.LearnerTbl['Age'])+#13+'Fees Owing: '
+floattostrf(dm.LearnerTbl['FeesOwing'],ffcurrency,7,2));
end; //if

dm.LearnerTbl.Next; //4
end; //5 end of while

end; //procedure

iii. Sample run: Enter a learner’s AdminNo here

NOTE:

 Up until this point, you have coded using a while loop that NAVIGATES through each record in the table so
you can code as per question for basic statisics/information.
 Try and find a pattern in your mind of how those ‘FAMOUS 5 LINES’ will be used for these type of questions
i.e. Questions which require you to sift through each record in order for you to find a solution.
 The rest of this Lesson 3 will cover code construct for:
o Inserting a new record
o Deleting a record
o Editing/updating a record.
7|P ag e “ A I M F O R E X C E L L E N C E ” … E C M
4. CODE CONSTRUCT ADDING/INSERTING A NEW RECORD – ACTIVITY:
a. Add the following components to the form:
I. Tpanel – clear the Caption
II. The following TLabels, TEdits, TRadioButtons, TSpinEdit and TButton must be added on the
panel:

RENAME AS BELOW:

edtAddAdmin

edtAddName

rbtnFemale

rbtnMale

spnAge

edtAddGrDiv

edtAddFeesOwing

btnAdd

***Code btnAdd:
III. Code btnAdd as follows:
procedure tform1.btnaddclick(sender: tobject);
begin
dm.learnertbl.last; //points to last record so that new record can be added after it
dm.learnertbl.insert; //set in insert mode

//now assign all new values as you retrieve from components to each field
dm.learnertbl['adminno']:= edtaddadmin.text;
dm.learnertbl['fullname']:= edtaddname.text;
//gender
if rbtnfemale.checked then
begin
dm.learnertbl['gender']:= 'F';
end;
if rbtnmale.checked then
begin
dm.learnertbl['gender']:= 'M';
end;
//age
dm.learnertbl['age']:=spnage.value;

dm.learnertbl['gradediv']:=edtaddgrdiv.text;
dm.learnertbl['feesowing']:= strtofloat(edtaddfeesowing.text);

//after retrieving all new values for the new record post and refresh
//post adds record to delphi dbgrid as well as in the Access table.
dm.learnertbl.post;
dm.learnertbl.refresh;
//userfriendly message
showmessage('new record added...');
end;

8|P ag e “ A I M F O R E X C E L L E N C E ” … E C M
IV. Sample:

N.B. Please make sure that you enter a new AdminNo (Primary key) and NOT one that
already exists every time you test the ADD button else you will get an error.

Reason: a primary key cannot be repeated.

_______________________________________________________________________________________________

5. CODE CONSTRUCT DELETING A RECORD – ACTIVITY:


In this example, we going to delete in 2 possible ways it could be tested/questioned:

First possible way it could be questioned:

I. Deleting the record the user points to it on the DBgrid using the mouse in runtime:
i. Add the following to the form:
 A panel – clear the Caption
 A TButton (btnDeleteSelectedRecord)

N.B. In runtime, after btnDeleteSelectedRecord is coded, the user will select the record to be
deleted as above by clicking up or down where the arrow is, then the following code will
allow for that selected record to be deleted from the table.

9|P ag e “ A I M F O R E X C E L L E N C E ” … E C M
***Code btnDeleteSelectedRecord:
ii. Code btnDeleteSelectedRecord as below:

procedure TForm1.btnDeleteSelectedRecordClick(Sender: TObject);


begin
dm.LearnerTbl.Delete; //this 1 line of code will delete the
record the user has selected on the
DBgrid using the mouse.
showmessage('Selected Record deleted successfully...');
end;

iii. Sample run: In my test run, I selected the last record K116.
After the run, that last record will not be in the table.

Second possible way it could be questioned:

II. Deleting a record that you search for when the user enters the AdminNo (primary key):
i. Add the following components:
 Tpanel – clear the Caption
 Add on the panel, a Tlabel, TEdit (edtDeleteAdminNo) and a
TButton (btnDeleteBySearch).

10 | P a g e “ A I M F O R E X C E L L E N C E ” … E C M
***Code btnDeleteSelectedRecord:
ii. Code btnDeleteBySearch as follows:
Allow the user to enter the AdminNo (primary key) of the record to delete.
The code must search for the record and thereafter delete when found. We will use
the ‘FAMOUS 5 LINES’ to search.

N.B. We will assume in this example that the AdminNo entered exists and therefore
you must enter an AdminNo from the existing table when testing. The code
below is NOT catering for a record not being found in this example.

procedure TForm1.btnDeleteBySearchClick(Sender: TObject);


var
sSearch: string;
begin
sSearch:= edtDeleteAdminNo.Text;

dm.LearnerTbl.First; //1
while not dm.LearnerTbl.eof do //2
begin //3
if sSearch = dm.LearnerTbl['AdminNo'] then
begin
dm.LearnerTbl.Delete; //deletes record when found
showmessage('Record Deleted...');
end; //if
dm.LearnerTbl.Next; //4
end; //5 end of while
end;

iii. Sample run:

11 | P a g e “ A I M F O R E X C E L L E N C E ” … E C M
6. CODE CONSTRUCT UPDATING/EDITING A RECORD – ACTIVITY:
Updating/editing records can be done or questioned in various ways:

 You may be asked to write code to allow the user to update many or all fields in the record.
 You may be asked to update a single field in a record.
 Etc.

In the following example, we will allow the user to update the selected records Fees Owing by an amount
entered by the user. That amount entered will be a payment made towards outstanding fees owing.

i. Add the following components:


 A TPanel – clear the Caption
 A TLabel, TEdit (edtUpdateAmount) and a TButton (btnUpdate) must be added on
the panel.

***Code btnDeleteSelectedRecord:
ii. Code btnUpdate as follows:
In runtime, the user will select on the DBgrid the record of the learner whose Fees Owing
needs to be updated by moving the mouse and clicking on the record.
In this example, I will select and update K112 so it should decrease from a fee balance of
R1500.

procedure TForm1.btnUpdateClick(Sender: TObject);


var
rAmountPaying:real;
begin
//retrieve amount from tedit
rAmountPaying:= strtofloat(edtUpdateAmount.Text);

dm.LearnerTbl.Edit; //sets in edit mode for the selected record only

//replaces the field for the selected record with the amount it was subtract the amount
paid
dm.LearnerTbl['FeesOwing']:= dm.LearnerTbl['FeesOwing'] - rAmountPaying;

showmessage('Record updated...');
end;

12 | P a g e “ A I M F O R E X C E L L E N C E ” … E C M
iii. Sample run:
N.B. Select record K112 fees owing went from R1500 to R1000.

______________________________________________________________________________________________

N.B.

 Now Grade 11 Learners, you have learnt:


o How to create a database with 1 table saved as a 2002-2003 version.
o How to setup and connect the database from Access to Delphi using a DataModule and its
components.
o And finally in this Lesson 3, you have learnt how to use code construct to find basic
statistics/information using the so-called ‘FAMOUS 5 LINES’ that loops through the table from the
first to the last record and code construct that uses specific database reserved words to
insert/delete/update records.
o You will be tested on this section and you will use this section for your PAT when it is released.
o Please make up further examples and practice.
o Part 2 which is SQLs will be done at a much later stage, maybe in the latter half of the year.

N.B. If you move the project folder at any time, you will find that the connection breaks because the
path/location of the database will be changed. All you have to do is go back to the datamodule and
click on the ADOCONNECTION you saved as conn and go to connectionString in the object inspector
and re-select the database connection steps….

13 | P a g e “ A I M F O R E X C E L L E N C E ” … E C M

You might also like