Lesson 3 db
Lesson 3 db
_______________________________________________________________________________________________
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:
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:
_______________________________________________________________________________________________
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)
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’]
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.
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
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
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.
_______________________________________________________________________________________________
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:
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.
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.
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;
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.
***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.
//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.
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