A pencil-and-paper workbook: design the tables first, learn to trust the data, then make Delphi walk through the records.
Before there is any Delphi, a database is just tidy paper: rows, columns and a rule for telling one row from another. In this unit you design tables with a pencil.
| Item | Price | How many | Supplier |
|---|---|---|---|
| Bread (brown) | R16 | 30 | Bakers, 021 555 0142 |
| Maize meal 5kg | R54.90 | 12 | Mills, 021 555 0177 |
| bread brown | 16.50 | a few | Bakers 021 555 0142 |
| Airtime R10 | 10 | lots | — |
| ItemID PK | ItemName | Category | Price | InStock |
|---|---|---|---|---|
| 1 | Vetkoek | Food | R8.00 | 24 |
| 2 | Pie | Food | R14.00 | 12 |
| 3 | Cooldrink | Drinks | R12.00 | 0 |
| 4 | Juice | Drinks | R10.50 | 0 |
| Type | Holds | Example |
|---|---|---|
| Text | letters, digits, symbols (up to 255) | Surname, cell number |
| Number (Integer) | whole numbers | InStock = 24 |
| Number (Double) | numbers with decimals | height 1.68 m |
| Currency | money, fixed decimals | Price = R14.00 |
| Date/Time | dates and times | date of birth |
| Yes/No | True or False (Boolean) | FeesPaid |
| AutoNumber | the database gives the next whole number | ItemID |
| Memo | long text, over 255 characters | a teacher's comment |
Write the best field type for each piece of data. Use the types from Learn It.
| Data | Best field type |
|---|---|
| The price of a vetkoek (R8.50) | |
| A learner's date of birth | |
| Whether the school fees have been paid | |
| The number of pies in stock | |
| A parent's cell number | |
| An admission number that the database hands out by itself | |
| A teacher's long comment on a learner |
Circle the field that would make the best primary key for each table.
| 1 | tblLearners (Surname, FirstName, Grade, AdmissionNo) | Surname Grade AdmissionNo |
| 2 | tblTaxis (Owner, Route, Colour, RegNo, a number plate) | Colour RegNo Route |
| 3 | tblBookCopies (Title, Author, Year, BarcodeNo) | Title BarcodeNo Author |
| 4 | tblItems (ItemName, Price, ItemID) | ItemName Price ItemID |
Tumi suggests using Surname as the primary key of tblLearners. Explain in two or three sentences why this is a bad idea.
Here are two records from a badly designed learner table:
| Name | Grade | Cell | Joined | Fees |
|---|---|---|---|---|
| Sipho Dlamini | Eleven | 082 123 4567 | last Tuesday | R450 paid |
| Sipho Dlamini | 11 | 0821234567 | 14/1/2026 | 450 |
The marshal at a taxi rank records, for every taxi, the data below. Give each a field name (no spaces) and a field type, and write PK next to the field you would use as the primary key.
| Data | Field name | Field type | Key? |
|---|---|---|---|
| Number plate | |||
| Driver's name | |||
| Route (for example Bellville to Cape Town) | |||
| Number of seats | |||
| Date the licence expires | |||
| Does it have a roadworthy certificate? |
One giant table that repeats everything wastes space and invites mistakes. Good databases split the data into several tables and link them with keys. You will learn the three kinds of link and draw them as diagrams (ERDs).
| Slip | Learner | Class teacher | Item | Amount |
|---|---|---|---|---|
| 1 | Naledi Mokoena | Mr Adams | Pie | R14 |
| 2 | Naledi Mokoena | Mr Adams | Juice | R10.50 |
| 3 | Ryan Pillay | Mrs Botha | Chips | R6.50 |
| 4 | Naledi Mokoena | Mr Adam | Vetkoek | R8 |
| 5 | Ryan Pillay | Mrs Botha | Water | R9 |
| Pair | One of the first has… | One of the second has… |
|---|---|---|
| Learner and school locker (one each) | ||
| Class and the learners in it | ||
| Learner and the subjects the learner takes | ||
| Taxi route and its taxis (each taxi has one route) | ||
| Learner and ID number |
| ClassID PK | Teacher |
|---|---|
| 11A | Mr Adams |
| 11B | Mrs Botha |
| LearnerID PK | Name | ClassID FK |
|---|---|---|
| 101 | Naledi | 11A |
| 102 | Ryan | 11B |
| 103 | Zinhle | 11A |
Circle the relationship for each pair.
| 1 | A learner and the one locker allocated to that learner | 1:1 1:M M:M |
| 2 | A school and the learners who attend it | 1:1 1:M M:M |
| 3 | Library members and books (members borrow many books over time; a book is borrowed by many members) | 1:1 1:M M:M |
| 4 | A taxi owner and the taxis he owns | 1:1 1:M M:M |
| 5 | Teachers and the classes they teach (a teacher teaches many classes; a class has many teachers) | 1:1 1:M M:M |
| 6 | A learner and the learner's passport number | 1:1 1:M M:M |
Each line describes a one-to-many link. Write the table that holds the foreign key and a sensible name for the foreign key field.
| Relationship | Table with the FK | FK field |
|---|---|---|
| One class has many learners (tblClasses, tblLearners) | ||
| One route has many taxis (tblRoutes, tblTaxis) | ||
| One parent has many children at the school (tblParents, tblLearners) | ||
| One doctor has many patients at a clinic (tblDoctors, tblPatients) |
A school library lends books to members. A member borrows many books over time, and a book is borrowed by many members over time. Each loan records the date the book left the library. Draw an ERD with three tables: tblMembers (MemberID, Name, Cell), tblBooks (BookID, Title, Author) and a linking table tblLoans. Show all fields, mark every PK and FK, and write 1 and M on the lines.
Every taxi is owned by one owner, but an owner may own several taxis. Every taxi works one route, but a route is served by many taxis. Draw an ERD with tblOwners, tblTaxis and tblRoutes. Give each table a primary key and at least two other fields, mark the foreign keys, and label the lines.
Learners 2 and 4 in tblLearners have ClassIDs 9B and 8C, but tblClasses holds only 8A, 8B and 9A. In three or four sentences explain what is wrong, what referential integrity means, and what the database should do if someone tries to delete class 9A while learners still belong to it. Use the word orphan.
A database is only as good as the data inside it. You will learn what makes data good, how a program can refuse bad data before it is saved, and what happens when data goes wrong through mistakes or crime.
| Name | Grade | Mark | Cell | Address |
|---|---|---|---|---|
| Lwazi Khumalo | 11 | 105 | 082 555 0191 | 12 Protea St |
| Megan Jacobs | Eleven | 64 | 083 555 0127 | 4 Oak Ave |
| 11 | 58 | 084 555 0163 | 9 Vine Rd | |
| Pieter Smit | 11 | 71 | 0845550 | 31 Rose St |
| Aisha Patel | 11 | 83 | 072 555 0188 | Flat 4, Kuils River |
| Characteristic | The question | Bad data looks like |
|---|---|---|
| Accuracy | Is it the right value, free from errors? | a mark of 65 typed as 56 |
| Correctness | Does it follow the rules and allowed values? | Grade holds “Eleven” |
| Currency | Is it up to date? | the address from before the family moved |
| Completeness | Is everything that is needed there? | no guardian name on 30 records |
| Check | What it tests | Example |
|---|---|---|
| Presence | something was entered | surname not blank |
| Type | right kind of data | Age holds digits only |
| Range | between a minimum and maximum | mark 0 to 100 |
| Format | right pattern | e-mail has an @ and a full stop |
| Lookup | value is in a list | one of the 9 provinces |
| Check digit | a calculated digit still matches | ID number, barcode |
if edtName.Text = '' then // presence
ShowMessage('Please enter a name')
else if (StrToInt(edtMark.Text) < 0) or (StrToInt(edtMark.Text) > 100) then // range
ShowMessage('The mark must be from 0 to 100')
else if Pos('@', edtEmail.Text) = 0 then // format
ShowMessage('The e-mail address needs an @');| Digit | 4 | 1 | 9 | 5 |
|---|---|---|---|---|
| Weight | 1 | 2 | 3 | 4 |
| Digit × weight | 4 | 2 | 27 | 20 |
Circle the data-quality characteristic that has been broken.
| 1 | A parent changed jobs last year but the school still has the old work number. | Accuracy Currency Completeness |
| 2 | A mark was typed as 56 but the test paper says 65. | Accuracy Correctness Currency |
| 3 | The Grade field holds “Eleven” although only the numbers 8 to 12 are allowed. | Correctness Currency Completeness |
| 4 | Thirty learners have no guardian name recorded. | Accuracy Completeness Currency |
Circle the check that matches each rule.
| 1 | A learner's mark must be from 0 to 100. | Range Type Format |
| 2 | An e-mail address must contain an @ and a full stop. | Format Presence Lookup |
| 3 | The surname field may not be left empty. | Presence Range Check digit |
| 4 | The province must be one of the nine names in a list. | Lookup Format Check digit |
| 5 | The last digit of a barcode is recalculated and compared. | Check digit Range Type |
Use the scheme from Learn It (weights 1, 2, 3, 4; MOD 10). For each five-digit code, work out the weighted sum of the first four digits, the check digit it should have, and decide whether the code is valid. Look at the first two codes: they use the same digits.
| Full code | Weighted sum | Check digit it should have | Valid? |
|---|---|---|---|
| 26086 | |||
| 62086 | |||
| 73512 | |||
| 90425 |
Write a function IsValidCode that receives a five-digit code as a String (such as '41953') and returns True if the fifth digit equals the check digit calculated from the first four (weights 1, 2, 3, 4; MOD 10). Hint: Ord(sCode[i]) - Ord('0') turns the character at position i into its digit.
In two or three sentences explain the difference between validation and verification. Then say whether a range check (0 to 100) would notice that a mark of 65 was typed as 56, and why.
During load shedding the power in the school tuck shop fails while the till is saving the day's sales, and the file is damaged. The next morning a helper types the day's takings as R4 120 when the correct amount was R1 420. In one short paragraph name the computer error and the human error, explain what effect they could have on the tuck shop owner, and say how each could be reduced.
(a) A hacker steals the ID numbers and cell numbers of 800 learners from a school database. Explain how this could harm a learner and what the school should do to protect such data. (b) A clinic's patient database is hit by ransomware. Explain what happens and why regular backups matter. (c) In one or two sentences say what SQL injection is and how a programmer can defend against it.
Now the tables come alive on screen. You will learn how four components pass the data from a file to a grid, and how a loop with First, Next and Eof visits every record.
| ItemID PK | ItemName | Category | Price | InStock |
|---|---|---|---|---|
| 1 | Vetkoek | Food | R8.00 | 24 |
| 2 | Pie | Food | R14.00 | 12 |
| 3 | Cooldrink | Drinks | R12.00 | 0 |
| 4 | Juice | Drinks | R10.50 | 0 |
| 5 | Chips | Snacks | R6.50 | 40 |
| 6 | Water | Drinks | R9.00 | 18 |
| 7 | Muffin | Food | R11.00 | 5 |
| 8 | Lollipop | Sweets | R1.50 | 60 |
procedure TdmTuck.DataModuleCreate(Sender: TObject);
begin
conTuck := TADOConnection.Create(Self);
conTuck.LoginPrompt := False; // no password box
conTuck.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source='
+ ExtractFilePath(Application.ExeName) + 'Tuck.mdb;';
conTuck.Connected := True;
tblItems := TADOTable.Create(Self);
tblItems.Connection := conTuck;
tblItems.TableName := 'tblItems';
tblItems.Active := True;
dsItems := TDataSource.Create(Self);
dsItems.DataSet := tblItems;
end;
// on the main form (OnShow, not OnCreate)
dbgItems.DataSource := dmTuck.dsItems;rTotal := 0; iCount := 0; // set up BEFORE the loop dmTuck.tblItems.First; while not dmTuck.tblItems.Eof do begin rTotal := rTotal + dmTuck.tblItems['Price']; // read the current record Inc(iCount); dmTuck.tblItems.Next; // move on, or the loop never ends end; if iCount > 0 then lblAvg.Caption := FloatToStrF(rTotal / iCount, ffFixed, 8, 2);
Trace the loop on the tuck-shop table printed in 4.1 (turn back to it). Write whether the price is above R10 and the values of iCount and iUnits after each record.
iCount := 0; iUnits := 0;
dmTuck.tblItems.First;
while not dmTuck.tblItems.Eof do
begin
if dmTuck.tblItems['Price'] > 10 then
begin
Inc(iCount);
iUnits := iUnits + dmTuck.tblItems['InStock'];
end;
dmTuck.tblItems.Next;
end;| ItemName | Price | Price > 10 ? | iCount | iUnits |
|---|---|---|---|---|
| Vetkoek | R8.00 | |||
| Pie | R14.00 | |||
| Cooldrink | R12.00 | |||
| Juice | R10.50 | |||
| Chips | R6.50 | |||
| Water | R9.00 | |||
| Muffin | R11.00 | |||
| Lollipop | R1.50 |
Using the same table, what appears in memOut? (FloatToStrF with ffFixed and 2 decimals shows R12.00 for 12.)
dmTuck.tblItems.First;
while not dmTuck.tblItems.Eof do
begin
if dmTuck.tblItems['InStock'] = 0 then
memOut.Lines.Add(dmTuck.tblItems['ItemName']
+ ' (R' + FloatToStrF(dmTuck.tblItems['Price'], ffFixed, 8, 2) + ')');
dmTuck.tblItems.Next;
end;This code should add up the value of the stock (price times number in stock) and display it, but it has four errors. Find them and write the corrections.
var
rValue : Real;
begin
rValue := 0;
while dmTuck.tblItems.Eof do
begin
rValue := rValue + dmTuck.tblItems['Price'] * dmTuck.tblItems['InStock'];
end;
lblValue.Caption := rValue;
end;Write code that finds the item with the highest price in tblItems and shows its name and price in lblDear (for example Pie: R14.00). Declare your variables.
Complete the connection and the table in the data module's OnCreate procedure so that the program opens Tuck.mdb in the same folder as the program (the DataSource is done for you).
procedure TdmTuck.DataModuleCreate(Sender: TObject); begin // ______ your connection and table code goes here ______ dsItems := TDataSource.Create(Self); dsItems.DataSet := tblItems; end;
A database is no use if you can only look at it. You will add, change and delete records from code, search for records with a loop, and learn the mistakes that quietly destroy data.
dmTuck.tblItems.Insert; // add a new item dmTuck.tblItems['ItemName'] := edtName.Text; dmTuck.tblItems['Price'] := StrToFloat(edtPrice.Text); dmTuck.tblItems.Post; dmTuck.tblItems.Edit; // change the current item dmTuck.tblItems['Price'] := 15; dmTuck.tblItems.Post;
bFound := False;
dmTuck.tblItems.First;
while (not dmTuck.tblItems.Eof) and (not bFound) do
begin
if UpperCase(dmTuck.tblItems['ItemName']) = UpperCase(edtFind.Text) then
bFound := True
else
dmTuck.tblItems.Next;
end;
if bFound then
lblPrice.Caption := FloatToStrF(dmTuck.tblItems['Price'], ffFixed, 8, 2)
else
lblPrice.Caption := 'Not found';dmTuck.tblItems.First;
while not dmTuck.tblItems.Eof do
begin
if dmTuck.tblItems['InStock'] < 10 then
dmTuck.tblItems.Delete // no semicolon: the else belongs to this if
else
dmTuck.tblItems.Next;
end;This code should add R2 to the price of every item in the Snacks category, but nothing is saved and the program sometimes freezes. Find three errors.
dmTuck.tblItems.First;
while not dmTuck.tblItems.Eof do
begin
if dmTuck.tblItems['Category'] = 'Snacks' then
begin
dmTuck.tblItems['Price'] := dmTuck.tblItems['Price'] + 2;
dmTuck.tblItems.Next;
end;
end;Trace the loop on the tuck-shop table printed in 4.1. Write whether the category is Drinks and the price of each item after its turn.
dmTuck.tblItems.First;
while not dmTuck.tblItems.Eof do
begin
if dmTuck.tblItems['Category'] = 'Drinks' then
begin
dmTuck.tblItems.Edit;
dmTuck.tblItems['Price'] := dmTuck.tblItems['Price'] + 1;
dmTuck.tblItems.Post;
end;
dmTuck.tblItems.Next;
end;| ItemName | Category | Category = 'Drinks' ? | Price after |
|---|---|---|---|
| Vetkoek | Food | ||
| Pie | Food | ||
| Cooldrink | Drinks | ||
| Juice | Drinks | ||
| Chips | Snacks | ||
| Water | Drinks | ||
| Muffin | Food | ||
| Lollipop | Sweets |
The table starts with the same 8 records as in 4.1. Trace this loop. For each pass write whether InStock is below 10, what the loop does, and how many records are left after the pass. Careful: after a Delete the pointer is on the next record.
dmTuck.tblItems.First;
while not dmTuck.tblItems.Eof do
if dmTuck.tblItems['InStock'] < 10 then
dmTuck.tblItems.Delete
else
dmTuck.tblItems.Next;| Pass | Record tested | InStock | Below 10? | Action | Records left |
|---|---|---|---|---|---|
| 1 | |||||
| 2 | |||||
| 3 | |||||
| 4 | |||||
| 5 | |||||
| 6 | |||||
| 7 | |||||
| 8 |
The user types the item name in edtName, the price in edtPrice and the category in cmbCategory when btnAdd is clicked. Write the code for the click that adds a new record (InStock starts at 0). Do not validate.
Write the code for btnFind that searches tblItems for the item named in edtFind (ignore capital letters). If found, show its price in lblPrice; otherwise show Not found. Stop looking as soon as it is found.
At the end of term the tuck shop deletes every item that has an InStock of 0 and a Category of Sweets. Write the loop, and ask the user for confirmation once before it starts (MessageDlg returns mrYes for Yes).
Real programs have more than one screen. Good programmers plan on paper before they open Delphi. You will break a job into forms, choose components, and plan what happens when each button is pressed.
frmItem.ShowModal; // in frmMain: the add form opens on top Close; // in frmItem: back to frmMain
Write the best component for each field on the Add Item screen. Use names such as Edit, ComboBox, SpinEdit, CheckBox, DateTimePicker, Memo, RadioGroup.
| The user enters… | Best component |
|---|---|
| The item name (any text) | |
| The category: Food, Drinks, Snacks or Sweets only | |
| The number in stock (0 to 500) | |
| Whether the item is on special | |
| The date the item was last delivered | |
| A long note about the supplier |
Sketch two forms for the tuck-shop program in the box below. frmMain must show all the items and let the user search and open the Add screen. frmItem must let the user enter the name, category and price and save or cancel. Label every component with a proper name (for example btnAdd) and draw an arrow, labelled with the event, from the button that opens frmItem. Then swap with a partner who “presses” your buttons: can they find their way?
Complete the code. btnAdd on frmMain opens frmItem. On frmItem, btnSave must check that the name is not empty (otherwise show a message and stay on the form); if it is valid it inserts the record with the name from edtName and the price from edtPrice, posts it and closes the form.
Three things go wrong in a two-form program. For each symptom give the most likely cause and how to fix it.
1. The compiler says Undeclared identifier: 'frmItem' inside frmMain's btnAdd code.
2. After pressing Cancel on frmItem, a half-empty record appears in the grid.
3. frmMain opens frmItem with frmItem.Show, and the user can click on frmMain while frmItem is open and start a second add.
Write the single line of Delphi (or the two or three lines) that each event must run.
| Event | The Delphi code that must run (one to three lines) |
|---|---|
| btnAdd on frmMain | |
| btnSave on frmItem (data valid) | |
| btnCancel on frmItem | |
| btnQuit on frmMain |
No notes, no computer. Show all your working. Write Delphi code neatly and use correct indentation.
A school sports database stores matches. Give the best field type for each piece of data.
| Data | Field type |
|---|---|
| The date of the match | |
| The name of the opposing school | |
| The final score of our team | |
| Whether the match was played at home | |
| A match number handed out automatically |
Learners may play several sports and every sport has many learners. Each sport has one coach, but a coach may coach several sports. Draw an ERD with four tables: tblLearners, tblSignups (a linking table), tblSports and tblCoaches. Give every table a primary key and at least one other field, mark the foreign keys, and write 1 and M on each line.
The table below is tblLearners. Trace the loop. Write whether the learner is in Grade 11 and the values of iTotal and iPass after each record.
| Name | Grade | Mark |
|---|---|---|
| Aphiwe | 10 | 62 |
| Bianca | 11 | 48 |
| Farai | 10 | 50 |
| Chloe | 11 | 75 |
| Dumisani | 12 | 90 |
| Esihle | 11 | 95 |
iTotal := 0; iPass := 0;
dmSchool.tblLearners.First;
while not dmSchool.tblLearners.Eof do
begin
if dmSchool.tblLearners['Grade'] = 11 then
begin
iTotal := iTotal + dmSchool.tblLearners['Mark'];
if dmSchool.tblLearners['Mark'] >= 50 then
Inc(iPass);
end;
dmSchool.tblLearners.Next;
end;| Name | Grade | Grade 11? | iTotal | iPass |
|---|---|---|---|---|
| Aphiwe | 10 | |||
| Bianca | 11 | |||
| Farai | 10 | |||
| Chloe | 11 | |||
| Dumisani | 12 | |||
| Esihle | 11 |
This code should add a new learner when btnSave is clicked. Find and correct three errors.
dmSchool.tblLearners['Name'] := edtName.Text; dmSchool.tblLearners['Grade'] := sedGrade.Value; dmSchool.tblLearners['Mark'] := edtMark.Text;
The loop below is meant to delete every learner with a mark under 60, but it has a mistake. Which learners remain, in order? Which learner was wrongly kept, and why?
dmSchool.tblLearners.First;
while not dmSchool.tblLearners.Eof do
if dmSchool.tblLearners['Mark'] < 60 then
begin
dmSchool.tblLearners.Delete;
dmSchool.tblLearners.Next;
end
else
dmSchool.tblLearners.Next;Write code that adds 5 marks to every Grade 11 learner in tblLearners, but never lets a mark go above 100. Save every change.
The user types a learner's name in edtFind. Write code that searches tblLearners and shows the learner's mark in lblMark, or Not found if there is no such learner.
Circle the data-quality characteristic that is broken.
| 1 | A record still shows the address the family left last year. | Accuracy Currency Completeness |
| 2 | A mark of 65 was captured as 56. | Accuracy Correctness Currency |
| 3 | A required cell-number field was left blank on 40 records. | Correctness Currency Completeness |
| 4 | The Grade field contains 15, but only 8 to 12 are allowed. | Accuracy Correctness Completeness |
A stock code has four digits and a check digit calculated with weights 1, 2, 3, 4 and MOD 10. (a) Calculate the check digit for 8 1 4 6. (b) Is the code 58403 valid? Show your working.
Explain in a short paragraph what the difference is between a human error and a computer error, give one example of each, and state one effect such errors may have on the data in a database.
A hospital's patient database is infected with ransomware. In a paragraph of about four sentences explain the effect on the hospital and its patients and how the hospital could have protected itself.
Explain what SQL injection is and name one way a programmer can reduce the risk.