0% found this document useful (0 votes)
209 views6 pages

Delphi Cram Sheet Gr12 IT

Cram sheet for matric learners for crunching content right before exams or basic outline on some functions you may have forgotten.

Uploaded by

d3luxyy
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)
209 views6 pages

Delphi Cram Sheet Gr12 IT

Cram sheet for matric learners for crunching content right before exams or basic outline on some functions you may have forgotten.

Uploaded by

d3luxyy
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/ 6

Grade 10 - 12 Delphi Commands

1. Data Types formatting. - Lowercase : Returns a string in lowercase form


Integer iNum := 1; rMoney : variable to be converted sStr := Lowercase('dElPhi'); // sStr =
String sName := ‘myString’; ffcurrency : used to specify currency 'delphi'
Real rNum := -1.78; 5 : Number of digits for Integer part - Position : Returns the index value of the
Char cChar := 'b'; 2 : Number of digits after decimal point first character in a specified substring that
Boolean bBool := 5 > 4; occurs in a given string
4.3.2 Convert to Currency(ffcurrency) iInt := pos('p','Delphi'); // iInt = 4
- Char Data type can only hold 1 character at a procedure TForm1.Button3Click(Sender: - Trim : removes whitesspaces from a string
time TObject); sStr := Trim(' Delphi '); // sStr =
var rMoney; 'Delphi'
2. Variables begin - Uppercase : Returns a string, in Uppercase
Variables are used to store data. They have to rMoney := 123.923858; format
created ('declared') before they can be edtOutput.Text := FloatToStrf(rMoney,ff sStr := Uppercase('dElPhi'); // sStr =
used('initialized') currency,5,2); // R123.92 'DELPHI'
end;
2.1 Declaration 4. Relational Operators
var sName, sSurname: string; 4.3.3 Convert to Fixed Decimal Place(ffFixed) = Equality iInt = 5
var iAge : integer; procedure TForm1.Button3Click(Sender: <> Inequality iInt <> 5
var rHeight : real; TObject); < Less Than iInt > 5
var rMoney; > Greater Than iInt < 5
2.2 Initialization begin <= Less than or Eqaul to iInt <= 5
var sName := 'Goku'; rMoney := 123.923858; >= Greater Than or Equal To iInt >= 5
var iAge := 149; edtOutput.Text := FloatToStrf(rMon
var rHeight : 1.89; ey,ffFixed,5,4); { $123.9200 } 5. Boolean Operators
end; not NEGATION not X
3. Naming Components and AND X and Y
4. Mathematics Function or OR X or Y
Component Prefix Include the *Math Uni t to make use of some of
TButton btn these functions such as floor, ceil, and power. 6. Random Numbers
TLabel lbl iVar1 := Random(2); // 0s and 1
TEdit edt - Abs : Returns the absolute value of a integer iVar2 := Random(10); // 0 to 9
TRichEdit red or real number iVar3 := 1+ Random(10); // 1 to 10
TCheckBox chk rReal := abs(-123,45) // Returns 123,45 iVar4 := 50+Random(250); // 50 to 250
TComboBox cmb - *Ceil : Rounds the value up to the nearest
TGroupBox grp whole number 7. Loops
TListBox lst iInt := ceil(123,65); // iInt = 124 7.1.1 For Loop from 1 to 10
TRadioGroup rgp iInt := ceil(123,45); //iInt = 124 for iInt:= 1 to 10 do
TRadioButton rbt - Dec : decrements an Integer variable by 1. begin
TSpinEdit spn iInt := 5; ShowMessage('Count:'+IntToStr(iInt));
TTrackBar trk Dec(iInt); //iInt = 4 end;
TStringGrid sgd - Div : used for integer division. For real 7.1.2 For Loop from 10 to 1
numbers use / for iInt:= 10 downto 1 do
4. Scope iInt := 10 div 3; // iInt = 3 begin
Refers to where a variable can be used. rReal := 12.34 / 4; // rReal = 3,085 ShowMessage('Count:'+IntToStr(iInt));
Local : Variable can be used inside procedure, - Frac: Returns the fractional part of a real end;
or function only. number
rReal := frac(4.41); // rReal = 0.41 7.2 Repeat from 1 to 10
procedure TForm1.Button1Click(Sender : - *Floor : Rounds the value down to the nearest iInt := 1;
TObject); whole number repeat
var sLocalVariable : string; iInt := floor(123.65); // iInt = 123 ShowMessage('iInt='+IntToStr(iInt));
begin iInt := floor(123,45); // iInt = 123 Inc(iInt);
sLocalVariable := 'sLocalVariable can be - Inc : Increments an Integer variable by until iInt = 11 ;
used in this procedure only'; specified value
end; iInt := 5; 7.3 While Loop from 1 to 10
Inc(iInt); // iInt = 6 iInt := 1;
Global : Variable can be used throughout whole - *Max: Determines maximum between two numbers while iInt <= 10 do
program, and will retain their value until iInt := Max(123,321); // iInt = 321 begin
program is closed. - *Min: Determines minimum between two numbers ShowMessage('iInt='+IntToStr(iInt));
iInt := Min(123,321); // iInt = 123 Inc(iInt);
unit Unit1; - Mod: The modulus, mods number1 by number2 end;
interface iInt := 10 mod 3; // iInt = 1
uses - *Power : Raises the first number to pwer of 8. Validation
SysUtils,; second 8.1 Validate a editbox for only strings
type Real := Power(2,3); // iInt = 8 procedure TForm2.Button1Click(Sender:
TForm1 = class(TForm) - Round function rounds a real-type value to an TObject);
private integer-type value var n : integer;
public iInt := Round(123.65); // iInt = 124; sInput : string;
end; iInt := Round(123.45); // iInt - 123; begin
var - Sqr: returns the square of a int or real sInput := Edit1.Text;
sGlobalVariable : string; iInt := srq(2); // iInt = 4 for n:= 1 to Length(sInput) do
implementation - Srqt: returns the square root begin
{$R *.dfm} iInt := sqrt(4); // iInt = 2 if not (sInput[n]
end. in['A'..'Z','a'..'z']) then
ShowMessage('Error! Letter at ' +
4. Data Type Conversions 4. Strings sInput[n] + ' not a character');
When worknig with different data types, a When indexing strings, the first character end;
conversion needs to be performed. starts at position 1. end;
- Copy: Returns a substring of a string
4.1 String sStr := Copy('Delphi',4,6); // sStr = phi 8.2 Validate a editbox for only numbers
- Convert a String into a Integer - Delete : Deletes a substring from a string procedure TForm2.Button1Click(Sender:
iNum := StrToInt(edtInput.Text); beginning at a specified point TObject);
- Convert a String into a Real Number sStr := 'Deplphi'; var n : integer;
iNum := StrToFloat(edtInput.Text); Delete(sStr,3,1); // sStr = 'Delphi' sInput : string;
- Insert : Inserts a substring into a string begin
4.2 Integer beginning at a specified point sInput := Edit1.Text;
- Convert a Integer into a String sStr := 'Dephi'; for n:=1 to length(sInput) do
edtInput.Text := IntToStr(iNum); Insert('l',sStr,3); // sStr = 'Delphi' begin
- Length : Returns the number of characters in a if not (sInput[n] < '0') or (sInput[n] >
4.3 Float string '9') then
- Convert a Float into a String iInt := Length('Delphi'); // iInt = 6 ShowMessage('Error! Letter at ' +
edtInput.Text := FloatToStr(rHeight); - LastDelimiter : Returns the position of the sInput[n] + ' not a number');
last occurence of a substring in a string. end;
4.3.1 FloatToStrf iInt := LastDelimiter('1','12341'); // iInt end;
Used to convert a Real Number to a String with = 5

www.sura.co.za/delphiza
Grade 10 - 12 Delphi Commands
9. Conditional Statements 10.8 Read 10 Names from Keyboard into an array,
9.1.1 If...then 10.3 Retrieving Values from Array and display the names in alphabetic order
if iAge >= 18 then ShowMessage(Names[1]); // Don var
ShowMessage('Adult'); ShowMessage(IntToStr(Numbers[5])); //5 i,j : integer;
s: string;
9.1.2 If..then...else 10.4 Assign a value into an array in the arrNames: Array[1..10] of string;
if iAge <= 18 then declaration: begin
ShowMessage('Teenager') var arrDays : array[1..7] of string = for i:=1 to 10 do
else ('Monday','Tuesday','Wednesday','Thursday', begin
ShowMessage('Adult'); 'Friday','Saturday','Sunday'); arrNames[i] := InputBox('Names','Type in
arrScore : array[1..3] of integer = (4,5,2); a name','');
9.1.3 Else If end;
if iAge >= 18 then 10.5 Insert a value into an array for i := 1 to 9 do
ShowMessage('Adult') for j:= i+1 to 10 do
else if(iAge < 18) and (iAge >= 12) then 10.5.1 Using a while loop: if arrNames[i] > arrNames[j] then
ShowMessage('Teenager') var i : integer; begin
else arrNumbers : array[1..10] of integer; s := arrNames[i];
ShowMessage('Child'); begin arrNames[i] := arrNames[j];
i := 1; arrNames[j] := s;
9.1.4 If Statement with Begin and End while i <= 10 do end;
if iAge >= 18 then begin for i:=1 to 10 do
begin arrNumbers[i] := i; redOut.Lines.Add(arrNames[i]);
ShowMessage('Adult'); i:=i+1 ; end;
sStr := 'In Matric or Campus'; end;
end end; 10.9 Search an Array
else if(iAge < 18) and (iAge >= 13) then const Marks : array[1..5] of real =
begin 10.5.2 Using a for loop: (85.34,86.74,75.43,76.23,95.23);
ShowMessage('Teenager'); var i : integer; var iInt : integer;sStr : string;
sStr := 'In High School'; arrNumbers : array[1..10] of integer; bFound : boolean;rFound : real;
end begin begin
else for i := 1 to 10 do sStr := InputBox('Enter in Search
ShowMessage('Child'); arrNumbers[i] := i; String','Enter string','');
sStr := 'In Primary School'; end; rFound := StrToFloat(sStr);
bFound := false;
9.2.1 Case Statement 10.5.3 Using a Repeat Loop iInt := 1;
case iAge of var i : integer; while (iInt <= High(Marks)) and (bFound =
14 : sStr := 'Grade 8'; arrNumbers : array[1..10] of integer; false) do
15 : sStr := 'Grade 9'; begin begin
16 : sStr := 'Grade 10'; i := 1; if Marks[iInt] = rFound then
17 : sStr := 'Grade 11'; repeat begin
18 : sStr := 'Grade 12'; arrNumbers[i] := i; ShowMessage('Found Item: ' + sStr + ' at
else i := i+1; pos ' + IntToStr(iInt));
sStr := 'Unknown Grade'; until i&lt;= 10; bFound := true;
end; end; end
else
9.2.2 Case Statement, with Number range 10.5.4 Using User Input ShowMessage('Not Found!');
case iAge of var Names : array[0..9] of string; inc(iInt);
0 .. 1 : sStr:= 'Infant'; iIndex : integer; end;
2 .. 4 : sStr:= 'Toddler'; begin end;
5 .. 13 : sStr:= 'Child'; for iIndex := 0 to 9 do
14 .. 18 : sStr := 'Teenager'; begin 10.10 Sort an Array ascending order
19 .. 60 : sStr := 'Adult'; Names[iIndex] := Input- const arrNum : array[1..7] of integer =
61 .. 100: sStr := 'Senior'; box('Names','Enter In A Name Below',''); (2,4,6,1,0,9,6);
101 .. 140 : sStr := 'Super'; end; var i,j,temp : integer;
141 .. 1000: sStr := 'Lengendary'; end begin
else for i := 1 to length(arrNum) -1 do
sStr := 'Immortal'; 10.6 Using the High / Low Functions for j := i + 1 to length(arrNum) do
end; Marks : array[1..5] of real = if (arrNum[i] &gt; arrNum[j]) then
(85.34,86.74,75.43,76.23,95.23); begin
9.2.3 Case Statement, with Begin and End - Low : The lowest value within the range of the temp := arrNum[j];
case iProvince of index type of the array. arrNum[j] := arrNum[i];
1 : begin ShowMessage('Low : ' + IntTStr(Low(Marks))); arrNum[i] := temp;
sProvince := 'Gauteng'; // 1 end;
sCapital := 'Johannesburg'; - High: The highest value within the range of end.
end; the index type of the array. For empty arrays,
2 : begin High returns –1. 10.11 Sort an Array descending order
sProvince := 'Kwa-Zulu-Natal'; ShowMessage('High: ' + IntStr(High(Marks))); const arrNum : array[1..7] of integer =
sCapital := 'Pietermaritzburg'; // 5 (2,4,6,1,0,9,6);
end; var i,j,temp : integer;
else * Note : The High and Low Functions are not begin
sProvince := 'Unknown'; limited to being used only with arrays, and can for i := 1 to length(arrNum) -1 do
sCapital := 'Unknown'; be used with Ordinal Types(integers) and for j := i + 1 to length(arrNum) do
end; strings. if (arrNum[i] &gt; arrNum[j]) then
begin
* Note : Both the if and case statement do the temp := arrNum[j];
same thing, with the exception that the case 10.7 Read 10 names from the keyboard into an arrNum[j] := arrNum[i];
statement only supports ordinal types. array and display the names in a rich edit arrNum[i] := temp;
case sStr of var i: Integer; end;
'kzn' : sProvince := 'Kwa-Zulu-Nata; nameArray : Array[1..10] of string; end.
end; begin
for i:=1 to 10 do 10.12 Find highest in an Array
begin const arrNum : array[1..7] of integer =
10. Arrays nameArray[i] := inputBox('Names','Type in (2,4,6,1,0,9,6);
10.1 Array Declaration a name',''); var
Numbers : array[1..10] of Integer; end; max,i : integer;
Names: array[1..5] of string; for i:= Low(nameArray) to High(nameArray) begin
Marks: array[0..4] of real; do max := arrNum[1];
begin for i := low(arrNum) to high(arrNum) do
10.2 Assigning Values to Array redOut.Lines.Add(nameArray[i]); begin
Names[1] := 'Don'; // string array end; if arrNum[i] > max then
for iInt:= 1 to 10 do // integer array end; max := arrNum[i];
begin end;
Numbers[iInt] := iInt; ShowMessage('Highest = ' + inttostr(max));
end; end;

www.sura.co.za/delphiza
Grade 10 - 12 Delphi Commands
9. Conditional Statements 10.8 Read 10 Names from Keyboard into an array,
9.1.1 If...then 10.3 Retrieving Values from Array and display the names in alphabetic order
if iAge >= 18 then ShowMessage(Names[1]); // Don var
ShowMessage('Adult'); ShowMessage(IntToStr(Numbers[5])); //5 i,j : integer;
s: string;
9.1.2 If..then...else 10.4 Assign a value into an array in the arrNames: Array[1..10] of string;
if iAge <= 18 then declaration: begin
ShowMessage('Teenager') var arrDays : array[1..7] of string = for i:=1 to 10 do
else ('Monday','Tuesday','Wednesday','Thursday', begin
ShowMessage('Adult'); 'Friday','Saturday','Sunday'); arrNames[i] := InputBox('Names','Type in
arrScore : array[1..3] of integer = (4,5,2); a name','');
9.1.3 Else If end;
if iAge >= 18 then 10.5 Insert a value into an array for i := 1 to 9 do
ShowMessage('Adult') for j:= i+1 to 10 do
else if(iAge < 18) and (iAge >= 12) then 10.5.1 Using a while loop: if arrNames[i] > arrNames[j] then
ShowMessage('Teenager') var i : integer; begin
else arrNumbers : array[1..10] of integer; s := arrNames[i];
ShowMessage('Child'); begin arrNames[i] := arrNames[j];
i := 1; arrNames[j] := s;
9.1.4 If Statement with Begin and End while i <= 10 do end;
if iAge >= 18 then begin for i:=1 to 10 do
begin arrNumbers[i] := i; redOut.Lines.Add(arrNames[i]);
ShowMessage('Adult'); i:=i+1 ; end;
sStr := 'In Matric or Campus'; end;
end end; 10.9 Search an Array
else if(iAge < 18) and (iAge >= 13) then const Marks : array[1..5] of real =
begin 10.5.2 Using a for loop: (85.34,86.74,75.43,76.23,95.23);
ShowMessage('Teenager'); var i : integer; var iInt : integer;sStr : string;
sStr := 'In High School'; arrNumbers : array[1..10] of integer; bFound : boolean;rFound : real;
end begin begin
else for i := 1 to 10 do sStr := InputBox('Enter in Search
ShowMessage('Child'); arrNumbers[i] := i; String','Enter string','');
sStr := 'In Primary School'; end; rFound := StrToFloat(sStr);
bFound := false;
9.2.1 Case Statement 10.5.3 Using a Repeat Loop iInt := 1;
case iAge of var i : integer; while (iInt <= High(Marks)) and (bFound =
14 : sStr := 'Grade 8'; arrNumbers : array[1..10] of integer; false) do
15 : sStr := 'Grade 9'; begin begin
16 : sStr := 'Grade 10'; i := 1; if Marks[iInt] = rFound then
17 : sStr := 'Grade 11'; repeat begin
18 : sStr := 'Grade 12'; arrNumbers[i] := i; ShowMessage('Found Item: ' + sStr + ' at
else i := i+1; pos ' + IntToStr(iInt));
sStr := 'Unknown Grade'; until i&lt;= 10; bFound := true;
end; end; end
else
9.2.2 Case Statement, with Number range 10.5.4 Using User Input ShowMessage('Not Found!');
case iAge of var Names : array[0..9] of string; inc(iInt);
0 .. 1 : sStr:= 'Infant'; iIndex : integer; end;
2 .. 4 : sStr:= 'Toddler'; begin end;
5 .. 13 : sStr:= 'Child'; for iIndex := 0 to 9 do
14 .. 18 : sStr := 'Teenager'; begin 10.10 Sort an Array ascending order
19 .. 60 : sStr := 'Adult'; Names[iIndex] := Input- const arrNum : array[1..7] of integer =
61 .. 100: sStr := 'Senior'; box('Names','Enter In A Name Below',''); (2,4,6,1,0,9,6);
101 .. 140 : sStr := 'Super'; end; var i,j,temp : integer;
141 .. 1000: sStr := 'Lengendary'; end begin
else for i := 1 to length(arrNum) -1 do
sStr := 'Immortal'; 10.6 Using the High / Low Functions for j := i + 1 to length(arrNum) do
end; Marks : array[1..5] of real = if (arrNum[i] &gt; arrNum[j]) then
(85.34,86.74,75.43,76.23,95.23); begin
9.2.3 Case Statement, with Begin and End - Low : The lowest value within the range of the temp := arrNum[j];
case iProvince of index type of the array. arrNum[j] := arrNum[i];
1 : begin ShowMessage('Low : ' + IntTStr(Low(Marks))); arrNum[i] := temp;
sProvince := 'Gauteng'; // 1 end;
sCapital := 'Johannesburg'; - High: The highest value within the range of end.
end; the index type of the array. For empty arrays,
2 : begin High returns –1. 10.11 Sort an Array descending order
sProvince := 'Kwa-Zulu-Natal'; ShowMessage('High: ' + IntStr(High(Marks))); const arrNum : array[1..7] of integer =
sCapital := 'Pietermaritzburg'; // 5 (2,4,6,1,0,9,6);
end; var i,j,temp : integer;
else * Note : The High and Low Functions are not begin
sProvince := 'Unknown'; limited to being used only with arrays, and can for i := 1 to length(arrNum) -1 do
sCapital := 'Unknown'; be used with Ordinal Types(integers) and for j := i + 1 to length(arrNum) do
end; strings. if (arrNum[i] &gt; arrNum[j]) then
begin
* Note : Both the if and case statement do the temp := arrNum[j];
same thing, with the exception that the case 10.7 Read 10 names from the keyboard into an arrNum[j] := arrNum[i];
statement only supports ordinal types. array and display the names in a rich edit arrNum[i] := temp;
case sStr of var i: Integer; end;
'kzn' : sProvince := 'Kwa-Zulu-Nata; nameArray : Array[1..10] of string; end.
end; begin
for i:=1 to 10 do 10.12 Find highest in an Array
begin const arrNum : array[1..7] of integer =
10. Arrays nameArray[i] := inputBox('Names','Type in (2,4,6,1,0,9,6);
10.1 Array Declaration a name',''); var
Numbers : array[1..10] of Integer; end; max,i : integer;
Names: array[1..5] of string; for i:= Low(nameArray) to High(nameArray) begin
Marks: array[0..4] of real; do max := arrNum[1];
begin for i := low(arrNum) to high(arrNum) do
10.2 Assigning Values to Array redOut.Lines.Add(nameArray[i]); begin
Names[1] := 'Don'; // string array end; if arrNum[i] > max then
for iInt:= 1 to 10 do // integer array end; max := arrNum[i];
begin end;
Numbers[iInt] := iInt; ShowMessage('Highest = ' + inttostr(max));
end; end;

www.sura.co.za/delphiza
Grade 10 - 12 Delphi Commands
11. 2D Array -FileExists: The fileexists function returns
11.1 Declare a 2D Array True if the given FileName file exists. 13.3 Loop through all records in a table
var arrNums : array[1..3,1..4] of integer; if not fileexists('Test.txt') then procedure TfrmCarRent.btnTotalStartKmC-
- arrNums : name of 2D array Showmessage('File does not exist'); lick(Sender: TObject);
- 1..3 : number of rows -ReWrite : Opens file as new var iSum : integer;
- 1..4 : number of columns ReWrite(myFile); begin
-Reset : Opens a file for Read Access iSum := 0;
11.2 Intialize 2D array with random values Reset(myFile); tblRentals.First;
procedure TForm1.btnInitializeClick(Sender: - Append : Opens a file for appending at end while not tblRentals.Eof do
TObject); Append(myFile); begin
var row,col : integer; - Read : Read one Letter at a time iSum := iSum + tblRentals['Start_Km'];
begin read(myFile,cChar); tblRentals.Next;
for row := 1 to 3 do - ReadLn : Reads a Line of Text and goes to Next end;
for col := 1 to 4 do Line redOutput.Clear;
begin readln(myFile,sStr); redOutput.Lines.Add('Total Start_Km = ' +
arrNums[row,col] := random(9)+1; - Rename : Changes the name of an external file. inttostr(iSum) + ' Kms');
end; Rename(myFile, 'Test1.txt'); end;
end; - Write : Writes to A File
write(myFile, 'Some Text Here '); 13.4 Count all the records in a table
11.3 Print the elements inside of the 2D - WriteLn : Writes to a File in a New Line procedure TfrmCarRent.btnTotalRecord-
Array writeln(myFile, 'Hello World'); sClick(Sender: TObject);
procedure TForm1.btnPrintElementsClick(Send- var iTotalRecords : integer;
er: TObject); begin
var row,col : integer; 12.2 Reading from a Text File iTotalRecords := 0;
str : string; - Sample Data Contained in the text file will tblRentals.First;
begin look like this. while not tblRentals.Eof do
for row := 1 to 3 do begin
begin elinks#Free Text-Based Console Browser inc(iTotalRecords);
str := ''; lynx#Customizable Web Browser tblRentals.Next;
for col := 1 to 4 do w3m#Open Source Web Browser end;
begin Note the delimiter (#) redOutput.Clear;
str := str + inttostr(arrNums[row,col]) + redOutput.Lines.Add('TotalRecords = ' +
' '; var inttostr(iTotalRecords));
end; myFile : textFile; end;
redOutput.Lines.Add(str); sStr,sBrowserName,sDescription : string;
end; iIndex : integer; There is a built-in method that does the exact
end; begin same thing called RecordCount:
if Not FileExists('sample-data.txt') then
11.4 Get the sum of rows in a 2D Array ShowMessage('File does not exist') procedure TfrmCarRent.btnRecordCount-
procedure TForm1.btnAddRowClick(Sender: else Click(Sender: TObject);
TObject); begin begin
var row,col,rowSum : integer; AssignFile(myFile,'sample-data.txt'); redOutput.Clear;
begin Reset(myFile); redOutput.Lines.Add('TotalRecords = ' +
for row := 1 to 3 do while not eof(myFile) do inttostr(tblRentals.RecordCount));
begin begin end;
rowSum := 0; Readln(myFile,sStr);
for col := 1 to 4 do iIndex := Pos('#',sStr); 13.5 Modify Commands
begin sBrowserName := Copy(sStr,1,iIndex-1); The modify commands, correspond to the SQL
rowSum := arrNums[row,col] + rowSum; sDescription := Copy(sStr,iIndex+1); Update, Insert and Delete, and allow you to make
end; end; changes to the table.
redOutput.Lines.Add('Sum of row:' + intto Closefile(myFile);
str(row) + ' = ' + end; tblPlayers.Edit // Puts the dataset in edit
inttostr(rowSum)); end mode
end; tblPlayers.Insert // Puts the dataset in
end; 12.3 Wrinting to a Text File insert mode
procedure TForm1.btnWriteClick(Sender: tblPlayers.Delete // Puts the dataset in
11.5 Get the sum of columns in a 2D Array: TObject); delete mode
procedure TForm1.btnAddColumnsClick(Sender: var myFile : textFile; tblPlayers.Post // Writes the change to
TObject); sLine : string; current record to the database
var row,col,colSum : integer; begin
begin AssignFile(myFile, 'output.txt'); 13.6 Inserting a Record into the table
for col := 1 to 4 do Append(myFile); The Insert statement is responsible for putting
begin sLine := edtInput.Text; the table into insert mode, and Post statement
colSum := 0; Writeln(myFile,sLine); is responsible for saving any changes.
for row := 1 to 3 do redOutput.Lines.Add(sLine);
begin CloseFile(myFile); procedure TfrmCarRent.btnInsertClick(Sender:
colSum := arrNums[row,col] + colSum; end; TObject);
end; begin
redOutput.Lines.Add('Sum of col:' + intto 13. ADO tblRentals.Insert;
str(col) + ' = ' + 13.1 Accessing a single column in the table tblRentals['Vehicle_ID'] := strtoint(edtVe
inttostr(colSum)); - Rental_ID is a column of integer values hicle_ID.Text);
end; - Start_Date is a column of data values tblRentals['Driver_ID'] := strtoint(edt-
end; redOutput.Lines.Add('Rental_ID:' + #9 + Driver_ID.Text);
inttostr(tblRentals['Rental_ID'])); tblRentals['Start_Km'] := strtoint(edt-
12. Text Files redOutput.Lines.Add('Start_Date:' + #9 + Start_Km.Text);
Text files stores ASCII Text, and are read as datetostr(tblRentals['Start_Date'])); tblRentals['Stop_Km'] := strtoint(edt-
strings. Stop_Km.Text);
13.2 Navigational Commands tblRentals['Start_Date'] := strToDate(edt-
12.1 Text File Functions Allows you to navigate records in the table Start_Date.Text);
-AssignFile : Assigns your Text File to a tblRentals.First // Moves pointer to the tblRentals['Stop_Date'] := strToDate(edt-
variable for Use first record Stop_Date.Text);
AssignFile(myFile,'Test.txt'); tblRentals.Prior // Moves pointer to record tblRentals.Post;
-CloseFile: Closes the file one before current record end;
CloseFile(myFile); tblRentals.Next // Moves pointer to the next
-EOF: Tests whether the file position is at the record
end of a file. tblRentals.Last // Moves pointer to the last
while not EOF(myFile) do record
begin
ReadLn(myFile,text); procedure TfrmCarRent.btnRentalsFirst-
ShowMessage(text); Click(Sender: TObject);
end; begin
tblRentals.First;
end;

www.sura.co.za/delphiza
Grade 10 - 12 Delphi Commands
13.7 Edit Recrods in a table 14.2 As 14.6 Having
procedure TfrmCarRent.btnEditClick(Sender: The as statement renames a column in the output: The Having statement is similar to the WHERE
TObject); Usage: statement, allowing columns to be filtered based
begin SELECT column AS renameHere FROM table; on a criteria, but with a few differences. The
tblRentals.Edit; HAVING statement is applied after the GROUP BY
tblRentals['Vehicle_ID'] := strtoint(edtVe 14.2.1 Renaming the output Column: Statement, whilst the WHERE statement is applied
hicle_ID.Text); SELECT Song AS renameSong from tblResults ; before the GROUP BY. Another difference is that
tblRentals['Driver_ID'] := strtoint(edt- the HAVING STATEMENT can filter aggregrate
Driver_ID.Text); 14.3 Between results. The syntax for this statement is as
tblRentals['Start_Km'] := strtoint(edt- The between statement selects values in a follows:
Start_Km.Text); certain range. Usage:
tblRentals['Stop_Km'] := strtoint(edt- Usage: SELECT column FROM table_name WHERE condi-
Stop_Km.Text); SELECT column1 FROM table BETWEEN value1 and tion GROUP BY column HAVING
tblRentals['Start_Date'] := strToDate(edt- value2 condition;
Start_Date.Text);
tblRentals['Stop_Date'] := strToDate(edt- 14.3.1 Show those DanceCoupleIDs that have a 14.6.1 For every TypeOfDance, get the Max Score
Stop_Date.Text); score in the range of 20 and 30: that is greater than 35:
tblRentals.Post; SELECT DanceCoupleID,Score FROM tblResults SELECT TypeOfDance,MAX(Score) FROM tblRe-
redOutput.Clear; WHERE Score BETWEEN 20 AND 30; sults GROUP BY TypeOfDance HAVING MAX
redOutput.Lines.Add('New Record Succesfully (Score) > 35;
Edited'); Which could have also been rewritten as:
end; SELECT DanceCoupleID,Score FROM tblResults 14.7 Delete
WHERE Score >= 20 AND Score <= 30; The DELETE statement will delete a row within a
13.8 DELETE A RECORD FROM THE TABLE table.
procedure TfrmCarRent.btnDeleteYearTwenty- 14.3.2 Show those Videos that where published Usage:
Click(Sender: TObject); beteween the dates 23 January 2015 and 31 DELETE FROM table WHERE condition;
var iCount : integer; December 2015: Example:
begin SELECT VideoTitle, DatePublished FROM Video DELETE FROM tblResults WHERE TypeOfDance
iCount := 0; WHERE DatePublished BETWEEN LIKE('%Swag%');
tblRentals.First; #2015/01/23# AND #2015/12/31#
while not tblRentals.Eof do 14.8 Distinct
begin 14.4 Dates The Distinct statement eliminates duplicate
if pos('2020',datetostr(tblRen- You can make use of Date in the following values from a column, and only returns distinct
tals['Start_Date'])) > 0 then ways values.
begin Usage:
tblRentals.Delete; 14.4.1 Select a Date from the table based on SELECT DISTINCT column1, colum FROM table;
inc(iCount); some criteria:
tblRentals.First; SELECT GameDate FROM tblGames WHERE 14.8.1 Show the different dance types:
end; GameDate=#2016/01/11# SELECT DISTINCT TypeOfDance FROM tblResults;
tblRentals.Next; Example:
end; 14.4.2 Select the current Date using NOW(): SELECT DISTINCT Province FROM tblTowns,
redOutput.Lines.Add(inttostr(iCount) + ' SELECT NOW(); tblDams WHERE tblTowns.DamID =
Records Deleted'); tblDams.DamID AND River = "Vaal River";
end; 14.4.3 Select the Day from a Date using DAY():
SELECT DAY(#2016/01/11#); 14.9 In
14.SQL The IN statement allows us to state which values
14.1 Aggregate Functions 14.4.4 Select the Month from a Date using we would like to see for a certain column.
An aggregate function performs some mathe- MONTH(): Usage:
matic operations on a column. SELECT MONTH(#2016/01/11#); SELECT column FROM table WHERE column
IN('value1','value2');
Usage : 14.4.5 Select the Year from a Date using YEAR():
SELECT AggregateFunction(ColumnName) FROM SELECT YEAR(#2016/01/11#); 14.9.1 All couples that used the Cha-Cha and
tableName; Salsa Dance :
Min : Returns the minimum value from a column: 14.4.6 Select those Players born in September: SELECT DanceCoupleID,TypeOfDance FROM
SELECT MIN(Score) from tblResults; SELECT Name, DateOfBirth FROM tblPlayers tblResults WHERE TypeOfDance
Max : Return the maximum value from a column: where Month(DateOfBirth) = 9; IN('Cha-Cha','Salsa');
SELECT MAX(Score) from tblResults;
Sum : Returns the sum from a column : 14.4.7 Show the age of each Dam: 14.10 Group By
SELECT SUM(Score) from tblResults; SELECT DamName, (Year(Now()) - YearComplet- The Group By statement is used when you have the
Avg : Returns the average from a column : ed) as Age from tblDams; repeating values occuring in Columns. It groups
SELECT AVG(Score) from tblResults; these multiple occurence of values, into
Count : Counts the Number of values in a column: 14.4.8 Insert a New Date into the table: disctinct values. It is often used with aggre-
SELECT Count(Song) from tblResults; INSERT INTO tblGames VALUES (76, gate functions.
#2017/12/24#, "HM008", 250, 5566); Usage:
When using Aggregate functions on more than one SELECT columnsFROM table WHERE condition
column, you must use the Group By Statement 14.5 Format GROUP BY column.
The Format statement, formats a number into a
14.1.1 Find how many times the "Cha-Cha" was specific format. Example:
danced per week : Usage: SELECT Week,Count(TypeOfDance),TypeOfDance
SELECT Week,Count(TypeOfDance) from tblRe- SELECT FORMAT(column1,1) FROM table; FROM tblResults WHERE
sults where TypeOfDance='Cha-Cha' GROUP BY TypeOfDance='Cha-Cha' GROUP BY Week;
Week; 14.5.1 Format a column to 2 Decimal Places:
SELECT FORMAT(Score,"0.00") from tblGames; SELECT Endangered, Count(*) AS CountAnimals
14.1.2 Find how many couples where Eliminated FROM tblCarnivores Group By
per week: 14.5.2 Working out the Average Score, and Endangered;
SELECT Week,Count(Result) from tblResults displaying to three decimal places
WHERE Result="Eliminated" GROUP BYWeek; SELECT DanceCoupleID, FORMAT(AVG(- SELECT Month(PaymentDate) AS MonthNum
Score),"0.000") AS AverageScore FROM FORMAT(Sum(GrossSalary-
14.1.3 Find which TypeOfDance yielded the tblResults GROUP BY DanceCoupleID; Deductions),"Currency") AS TotalAmountPaid
highest score : FROM tblPayments GROUP BY MONTH
SELECT TypeOfDance,AVG(Score) FROM tblRe- 14.5.3 Using Format with "Currency": (PaymentDate);
sults GROUP BY TypeOfDance ORDER BY AVG(- SELECT MONTH(PaymentDate) as MonthNum
Score) desc; FORMAT(Sum(GrossSalary-
Deductions),"Currency") AS TotalAmountPaid
14.1.4 Display the names and average skill FROM tblPayments GROUP BY MONTH
levels of all teams with an average skill level (PaymentDate);
of more than 6 :
SELECT TeamName, Round(Avg(SkillsLevel),1)
AS AverageSkillsLevel FROM tblPlayers GROUP
BY TeamName HAVING Avg(SkillsLevel) > 6;

www.sura.co.za/delphiza
Grade 10 - 12 Delphi Commands
14.11 Insert 14.16 Where 15.6 Add 10 Days
The INSERT statement allows us to add a row into The Where clause allows us to specify criteria, procedure TForm2.Button1Click(Sender:
a table. to narrow down our results to what we want. TObject);
Usage: Usage: var myDate : TDateTime;
INSERT INTO table(column1,column2) SELECT column FROM table WHERE criteria; begin
VALUES(value1,value2); myDate := EncodeDate(2021,01,30);
15.Dates and Time myDate := incday(myDate,10);
Example : Getting the current date and time Richedit1.Lines.Add(datetostr(myDate));
INSERT INTO tblResults //2021/02/09
(RoutineNo,Week,Round,DanceCoupleID,TypeOf- procedure TForm2.Button1Click(Sender: end;
Dance,Song,Score,Result) VALUES TObject);
('120','13','2','15','Classical','Symphony var 15.7 Subtract 10 days
5','40','Eliminated'); myDate,myTime : string; procedure TForm2.Button1Click(Sender:
begin TObject);
You can also use the INSERT statement like this myTime := TimeToStr(Time); // 18:45:19 var myDate : TDateTime;
Usage: myDate := DateToStr(Date); // 2020/09/01 begin
INSERT INTO table values(value1, value2); Richedit1.Lines.add(myTime + ' ' + myDate := EncodeDate(2021,01,30);
Example: myDate); myDate := incday(myDate,-10);
INSERT INTO tblGames VALUES (76, end; Richedit1.Lines.Add(datetostr(myDate));
#2017/12/24#, "HM008", 250, 5566); //2021/01/20
15.1 Isolating the Day, Month and Year end;
14.12 Like procedure TForm2.Button1Click(Sender:
The Like operator allows us to search for a TObject); 16. OOP
matching pattern within a column. var Class Definition
Usage: myDate,myTime,sYear,sMonth,sDay : string; type
SELECT column FROM table WHERE column LIKE begin TVideo = class
pattern myTime := TimeToStr(Time); // 18:45:19 private
myDate := DateToStr(Date); // 2020/09/01 fvideoname : string;
It works alongside two wildcards: sYear := copy(myDate,1,4); // 20 fcomments : string;
% – The percent sign represents zero, one, or sMonth := copy(myDate,6,2); // 09 flikes : integer;
multiple characters sDay := copy(myDate,9,2); // 01 fdislikes : integer;
_ – The underscore represents a single character Richedit1.Lines.Add(sDay + ' ' + sMonth + frating : integer;
' ' + sYear); public
14.12.1 Find all Songs that start with B: end; constructor create(sname : string);
SELECT Song from tblResults where SONG procedure AddNewComment(scomment,sdate :
LIKE('B%'); 15.2 Formatting the Output string);
15.2.1 Format Example 1 procedure SetRating;
14.12.2 Find all the songs that contain the word procedure TForm2.Button1Click(Sender: function GetRating : string;
‘Love’ within them: TObject); procedure addLike;
SELECT Song from tblResults where SONG begin procedure addDislike;
LIKE('%LOVE%'); Richedit1.Lines.Add(formatdate- function tostring : string;
time('d/m/y',Date)); // 1/9/20 end;
14.12.3 Find all RoutineNos that obtained a end;
score of 30 or greater: 16.1 Class Constructor
SELECT RoutineNo,Score from tblResults WHERE 15.2.1 Format Example 1 constructor tvideo.create(sname: string);
Score LIKE('3_'); procedure TForm2.Button1Click(Sender: begin
TObject); fvideoname := sname;
14.13 Order By begin flikes := 0;
The order by statement is used to arrange output Richedit1.Lines.Add(formatdatetime('dd/m- fdislikes := 0;
in alphabetical order. When the order by m/yyyy',Date)); //01/09/2020 end;
statement is not specified, results from the end;
table are displayed in the order they are found. 16.2 Class Procedure with Parameters
With order by you can specify Ascending or 15.2.1 Format Example 1 procedure tvideo.AddNewComment(scomment:
Descending order: procedure TForm2.Button1Click(Sender: string; sdate: string);
Usage: TObject); begin
SELECT column FROM table WHERE criteria begin fcomments := #13 + scomment + #9 + sdate +
Order By column Richedit1.Lines.Add(formatdatetime('dd mm #13;
yyyy',Date)); //01 09 2020 end;
Example: end;
SELECT DanceCoupleID,TypeOfDance from 16.3 Class Function
tblResults where result = 15.2.1 Format Example 1 function tvideo.GetRating;
"Safe" ORDER BY TypeOfDance desc; procedure TForm2.Button1Click(Sender: var i : integer;
TObject); sline : string;
14.14 Select begin begin
The select statement retrieves data from the Richedit1.Lines.Add(formatdate- sLine := '';
table, based on the column you specify. time('hh:mm',Time)); //18:56 for i:= 0 to frating do
Usage: end; begin
SELECT column FROM table; sline := sline + '*';
15.3 Add DateUtils to uses clause to use: end;
14.14.1 Select Single Column from a Table: bLeapYear := isLeapYear(2009); // returns result := sline;
SELECT Song FROM tblResults ; true or false for a leap year end
bIsValid := isValidDate(2014,2,29); // true
14.14.2 Select Specific Column : or false if valid date in the month and year 17. Misc
SELECT TypeOfDance,Song,Score FROM tblRe- NumDays:=DaysInAMonth(2013,2);
sults; lblMsg.caption:=dateToStr(Today); Getting a value from a comboxbox, or listbox:
lblMsg.caption:=dateToStr(Tomorrow);
14.14.3 Select All Columns from a Table : lblMsg.caption:=dateToStr(Yesterday); String name := cmblist.text or
SELECT * FROM tblResults ; cmbList.Items[cmbList.ItemIndex] – retrieve
the selected item in the combo box.
14.15 Update 15.4 Isolate as an integer
The UPDATE statement allows us to update a field iYear:= YearOf(date); 18. Escape Sequences for formatting output
value within a table. iMonth:=MonthOf(Date);
Usage: iDay:=DayOf(Date); #9 – tab spaces in output
UPDATE table SET column WHERE condition; #13#10 – new line in output
15.5 Using EncodeDate to set custom date
Example: procedure TForm2.Button1Click(Sender:
UPDATE tblResults SET TypeOfDance='Swag' TObject);
WHERE RoutineNo='120'; var myDate : TDateTime;
begin
myDate := EncodeDate(2021,01,30);
Richedit1.Lines.Add(datetostr(myDate));
//2021/01/30
end;

www.sura.co.za/delphiza

You might also like