0% found this document useful (0 votes)
2 views

Databases in Delphi Summary

The document provides a comprehensive guide on using Microsoft Access databases with Delphi, detailing the steps to create and connect a database, set up data modules, and manage data controls. It includes instructions for inserting, editing, deleting records, and traversing tables, along with sample code for various operations. Additionally, it covers best practices for naming conventions and database structure to ensure compatibility with Delphi.
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)
2 views

Databases in Delphi Summary

The document provides a comprehensive guide on using Microsoft Access databases with Delphi, detailing the steps to create and connect a database, set up data modules, and manage data controls. It includes instructions for inserting, editing, deleting records, and traversing tables, along with sample code for various operations. Additionally, it covers best practices for naming conventions and database structure to ensure compatibility with Delphi.
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/ 11

DATABASES IN DELPHI

Microsoft Access Database


• Make sure you create the database as a 2003 version (with the .mdb extension)
• Use the tbl prefix when naming your tables.
• Don’t use spaces in your field names (use underscores or no spaces).
• Don’t use Name as a field name, rather use FirstName or something similar.
• Change your field sizes to suitable values.

Connecting a Database to Delphi Project


Step 1: Data Module
• Create a new Data Module (File->New->Other->Delphi Files)
• Give the Unit file a name at the top (dmXXXXXXXX_U)
• Save as that same name (File->Save As-> use name from above)

Step 2: Setup Data Module


• Change the Name property (in Object Inspector) of the Data Module (dmXXXXXX)
• Place the following components onto the Data Module
o ADOConnection (dbGo menu)
o ADOTable (dbGo menu)
o Data Source (Data Access menu)

Step 3: Setup Connection


• Change the following properties of the ADOConnection (via the Object Inspector)
o Change the Name (conXXXXXX)
o Give a ConnectionString (click on ... then click Build)
▪ Select the Jet option (Microsoft Jet 4.0 OLE DB Provider) then Next
▪ Select the database (click on ... & browse for database file) then OK
NOTE: Make sure the database file is in the same folder as Delphi files
▪Remove all the text in front of the database name (so that it always
refers to the folder that contains the Delphi files, even if it gets moved
to a different location)
▪ Test Connection to see if it works then click Next
▪ Deselect default option and select Read/Write option then click OK
twice to close dialog
o Set the LoginPrompt to false

1
Step 4: Setup ADOTable
• Change the following properties of the ADOTable (via the Object Inspector)
o Change the Name (tblXXXXX)
o Change the Connection to the ADOConnection you set up in Step 3
(conXXXXXX)
o Change the TableName to one of the databases table’s name
o Change the Active property to True

Step 5: Setup DataSource


• Change the following properties of the DataSource (via the Object Inspector)
o Change the Name (dscXXXXX)
o Change the DataSet to the table from Step 4 (tblXXXXX)
NOTE: If you have multiple tables then repeat steps 4 and 5 (with different ADOTables and
DataSources) for each table (Name and TableName will be different).

Click File -> Save All

NOW GO TO MAIN FORM


Step 6: Link the Form to the Data Module
• At the top of the form's code, under uses, add the name of the data module's Unit
name to the list:
Example: Uses Windows, Messages, SysUtils, ...., dmXXXXXXX_U ;

Step 7: Add Data Controls like a DBGrid (from Data Controls menu) and give them
suitable names (dbgXXXXX)

Step 8: Setup DBGrid or other Data Controls


• Change the DataSource of your Data Control (dbgXXXXX) to the Data Source from
step 5.
NOTE: It refers to data module name<dot>data source name (dmXXXXXX.dscXXXXX)
You should see the tables fields and records in the DBGrid. Do this for other Data Controls
you may add as well as change other properties that may be required like FieldName, etc.

Step 9: Change Column Widths


• Right click on DBGrid and select Columns Editor...
o Right click in the white space and select Add All Fields
o You should see a list of items for each field. Click on one field and you
should notice the Object Inspector contains the property for just that field.
▪ Change the Width of each field so you can see all the fields and their
contents clearly in the DBGrid.

2
Using a Data Module
All interaction with the database is done with the ADOTable. If the database connection is
done directly in the form then you simply need to use the ADOTable name:
Example: tblCD.Active := True ;

If the ADOTable has been created on a data module, then you access the ADOTable via
the data module:
Example: dmDatabase.tblCD.Active := True ;

If you are referring to the ADOTable with multiple lines of code, it is easier to use the with
statement:
Example:
with dmDatabase do
begin
tblCD.Active := True ;
tblCD. ……
end;

Sorting the table


• Use the Sort property
• String consists of the field name (as it is spelt in the database) followed by ASC for
ascending order (smallest to biggest) or DESC for descending order (biggest to
smallest)
• NOTE: ASC or DESC must be in capital letters.
• If there are multiple sort criteria, then separate each field by a comma.
Example:
dmDatabase.tblCD.Sort := ‘Artist ASC’ ;

tblPeople.Sort := ‘Surname ASC, Firstname ASC’ ;

3
Traversing the table
• Used when you need to go through each record in a table in order to find a record,
or calculate an average of a filed, etc.

General Structure – Traverse a table

//make sure ADOTable is active, if not the <ADOTable>.Active := true


<ADOTable>.First ; //moves pointer to first record
while NOT <ADOTable>.EOF do //loop until end of table
begin //always need a begin and end
//code required to work with ONE record
<ADOTable>.Next ; //moves pointer to next record
end ;

Method Name Description


First
Example: tblCD.First ; Moves pointer to first record in table.

Last
Example: tblCD.Last ; Moves pointer to last record in table.

EOF Returns TRUE if pointer is at the end of the


Example: if tblCD.EOF = True then table or FALSE if pointer is not at the end.
Next
Example: tblCD.Next ; Moves pointer to next record in table.

Prior
Example: tblCD.Prior ; Moves pointer to previous record in table.

RecordCount
Example: iNum := tblCD.RecordCount ; Returns the number of records in a table.

• To obtain the value of a particular field, based on where the pointer is at:
o ADOTable, followed by square brackets with name of the field (as it appears
in the database) in single quotes inside the square brackets.
<ADOTable> [ ‘Field_Name’ ]
o Data type of the field in the database will be the data type that is returned:
▪ Text fields will return a string
▪ Number fields will return an integer or real depending on format
▪ Currency fields will return a real
▪ Date/Time field will return a TDateTime
▪ Yes/No field will return a Boolean
Example: iNum := tblPeople[ ‘Age’ ] ;
showmessage( tblCD[ ‘Artist’ ] + #9 + FloatToStr( tblCD[ ‘Price’ ] ) ) ;

4
• Examples of traversing a table in order to calculate an average of a field:
Sample Code – Calculating an Average

iCount := 0 ;
iSum := 0 ;
tblPeople.First ; //go to first record in table
while NOT tblPeople.EOF do //loop until end of the table
begin
if tblPeople[ ‘Group’ ] = ‘Admin’ then //check if record is Admin person
begin
iSum := iSum + tblPeople[ ‘Points’ ] ; //sum the points
inc( iCount ) ; //count the number of admin people
end; //end of if
tblPeople.Next ; //move to next record
end; //end of while
rAve := iSum / iCount ; //calculate average
showmessage( ‘Average points of admin group is ‘ + FloatToStr( rAve) ) ; // display Average

Code finds the average points (integer field) of only the records in the database in the Admin group (string
field). If you wanted to find average points of ALL the records in table then you can remove the If statement
as well as using the iCount variable. Average calculation can be done using:
rAve := iSum / tblPeople.RecordCount ;.
You need an iCount variable if counting specific records as in the example shown above.

• Examples of traversing a table in order to find and display multiple records:


Sample Code – Searching for multiple records

tblPeople.First ; //go to first record in table


while NOT tblPeople.EOF do //loop until end of the table
begin
if tblPeople[ ‘Group’ ] = ‘Admin’ then //check if record is Admin person
begin
memDisplay.Lines.Add( tblPeople[ ‘Surname’ ] ); //display surname
end; //end of if
tblPeople.Next ; //move to next record
end; //end of while

Code displays the surnames (string field) of only the records in the database in the Admin group (string
field).

5
• Examples of traversing a table in order to find ONE specific record:
Sample Code – Searching for ONE record

bFound := False ; //Boolean variable to indicate if record has been found


tblPeople.First ; //go to first record in table
while (NOT tblPeople.EOF ) AND (bFound = False) do //loop til endof table OR record is found
begin
if tblPeople[ ‘PersonID’ ] = 3654 then //looking for record with ID of 3654
begin
bFound := True ; //Record has been found, this will also end the while loop
<code> //Code that must execute if record is found.
end //end of if
else tblPeople.Next ; //only need to move to next record if you still looking
end; //end of while

if bFound = False then //if Boolean still false at this point, then record was never found
begin
<code> //Code that must execute if record is NOT found.
showmessage( ‘Record not found’ ) ;
end ; //end of if

Yellow highlighted code indicates changes to scenario when compared to searching for multiple records.

Inserting a NEW record


• Put ADOTable into Insert mode: <ADOTable> .Insert ;
• Insert values into the relevant fields.
o Make sure you assign values of the correct data type.
o Make sure required fields have a value.
o Make sure primary key field has a value not currently being used in the table.
• Put ADOTable into Post mode: <ADOTable> .Post ;
Sample Code – Inserting a NEW record

tblPeople.Insert ; //table in Insert mode


tblPeople[ ‘Surname’ ] := ‘Long’ ; //assign values to fields
tblPeople[ ‘BirthDate’ ] := StrToDate( ‘2000/11/21’ ) ;
tblPeople[ ‘Points’ ] := 78 ;
…….
tblPeople.Post ; //post results to the table

6
Creating a unique primary key
• You can use the searching for ONE record algorithm in order to determine if the
primary key given is not already in the table.
• If the primary key field is a number field then the following can be used to create a
new unique value:
Example:
tblPeople.Sort := ‘PersonID ASC’ ; //Sort on primary key
tblPeople.Last ; //go to last record, which will be largest value
iNewID := tblPeople[ ‘PersonID’ ] + 1 ; //get last primary key & + 1 to it

Editing an existing record


• Put ADOTable into Edit mode: <ADOTable> .Edit ;
• Change values of the relevant fields.
o Make sure you assign values of the correct data type.
o Make sure primary key field has a value not currently being used in the
• Put ADOTable into Post mode: <ADOTable> .Post ;
Sample Code – Editing an existing record

tblPeople.Edit ; //table in Edit mode


tblPeople[ ‘Points’ ] := tblPeople[ ‘Points’ ] + 25 //assign changes to fields
tblPeople[ ‘Group’ ] := ‘Admin’ ;
…….
tblPeople.Post ; //post results to the table

Editing multiple records in a table


• Use the traverse algorithm
• then when pointer is at each record that requires changing
o Put into edit mode
o Make changes
o Post results
• Move to next record.

7
Sample Code – Editing multiple records

tblPeople.First ; //go to first record in table


while NOT tblPeople.EOF do //loop until end of the table
begin
if tblPeople[ ‘Group’ ] = ‘Admin’ then //check if record is Admin person
begin
tblPeople.Edit; //go into Edit mode for this record
tblPeople[ ‘Points’ ] := tblPeople[ ‘Points’ ] + 10 ; //add 10 to points
tblPeople.Post; //post results for this record change
end; //end of if
tblPeople.Next ; //move to next record
end; //end of while

Code increases the points by 10 of all the records of people in the Admin group.

Deleting a record
• Make sure pointer is at the record that you want to remove
• Call the delete method: <ADOTable> .Delete ;
Example:
tblPeople.First ;
tblPeople.Delete ; //delete the first record

Deleting multiple records in a table


• Use the traverse algorithm
• then when pointer is at each record that requires removing
o Call the Delete method
o ELSE Move to next record.
NOTE: The Delete method removes a record and automatically moves pointer to next
record. If you delete multiple records, and you have the delete method followed by the next
method, then you will skip the record under the one you just deleted.

In other words,
First – pointer at record 1
Delete – record 1 removed and pointer moves to record 2
Next – pointer moves to record 3 (hence we have skipped record 2).

8
Sample Code – Deleting multiple records

tblPeople.First ; //go to first record in table


while NOT tblPeople.EOF do //loop until end of the table
begin
if tblPeople[ ‘Group’ ] = ‘Admin’ then //check if record is Admin person
begin
tblPeople.Delete; //delete this record
end
else tblPeople.Next ; //ELSE move to next record
end; //end of while

Code deletes all records of those in the Admin group. NOTE: Else move to next.
If you do not use the Else in this case, if there are TWO admin records straight after each other, the second
one will be skipped.

9
EXTRA – Connecting to database using code
Step 1: Data Module <same as before>
• Create a new Data Module (File->New->Other->Delphi Files)
• Give the Unit file a name at the top (dmXXXXXXXX_U)
• Save as that same name (File->Save As-> use name from above)

Step 2: Add Units


• Under Uses, add ADODB and DB

Step 3: Declare your components


• Under Public declare the following components (under Public because we want our
main unit to be able to access these components from the main unit)
o conXXXXXX : TADOConnection ; //connect to Database
o tblXXXXXX : TADOTable ; //connects to table in DB
o dscXXXXXX : TDataSource ; //connects table to Data Controls
• Use your own names for the XXXXXX part.
• If you have other tables in the database, then declare multiple TADOTables and
TDataSources for each table.

Step 4: Setup Connection


• Go to Events of your Data Module and double click on open area next to the
OnCreate event. You should be at the code section for a procedure like below:
o procedure TXXXXXXX.DataModuleCreate(Sender: TObject);
• Write the following code to setup your ADO Connection:
o conXXXXXX := TADOConnection.Create( dmXXXX ) ;
//Change dmXXXX to the Name property of your Data Module (NOT Unit name)
o conXXXXXX.Close ; //make sure connection is closed
o conXXXXXX.ConnectionString :=
‘Provider=Microsoft.Jet.OLEDB.4.0;Data Source=XXXXXXX.mdb;’
+ ‘Mode=ReadWrite;Persist Security Info=False’ ;
//Change the XXXXXX.mdb to name of your MS Access database
//make sure that database is stored in the same folder as the Delphi files
o conXXXXXX.LoginPrompt := False ;
o conXXXXXX.Open ;

Step 5: Setup ADOTable


• Add the following code next:
o tblXXXXXX := TADOTable.Create( dmXXXX ) ;
//Change dmXXXX to the Name property of your Data Module (NOT Unit name)
o tblXXXXXX.Connection := conXXXXXX ;
o tblXXXXXX.TableName := XXXXX ;
// XXXXX refers to name of table in MS Access DB you want to connect to
o tblXXXXXX.Active := True ;
10
Step 6: Setup DataSource
• Add the following code next
o dscXXXXXX.DataSet := tblXXXXXX ;
NOTE: If you have multiple tables then repeat steps 5 and 6 (with different ADOTables and
DataSources) for each table (Name and TableName will be different).

Click File -> Save All

NOW GO TO MAIN FORM


Step 7: Link the Form to the Data Module
• At the top of the form's code, under uses, add the name of the data module's Unit
name to the list:
Example: Uses Windows, Messages, SysUtils, ...., dmXXXXXXX_U ;

Step 8: Add Data Controls like a DBGrid (from Data Controls menu) and give them
suitable names (dbgXXXXXX)

Step 9: Setup DBGrid or other Data Controls


• Go to Events of your main form and double click on open area next to the
OnActivate event. You should be at the code section for a procedure like below:
o procedure TXXXXXXX.FormActivate(Sender: TObject);
• Write the following code in this procedure
o dbgXXXXXX.DataSource := dmXXXX.dscXXXXXX ;
//dmXXXX refers to Name property of your Data Module (NOT Unit name)
// and dscXXXXXX refers to data source you created on that Data Module
• You can also set the column widths of each field in the DBGrid
o dbgXXXXXX.Columns[ 0 ].Width := 30 ; //1st column
o dbgXXXXXX.Columns[ 1 ].Width := 80 ; //2nd column
o dbgXXXXXX.Columns[ 4 ].Width := 50 ; //5th column, etc

You should see the table’s fields and records in the DBGrid when the program is executed.

You might also like