8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
1/347
-
I n cl u d ed i n T h i s Ch a p t er :
n The Relational Model n What is a Database?
n Along Came Codd n Data Structure m DataIntegrity q Data Manipulation
The database is ubiquitous in modern information processing; data is,stored in collections of some type in nearly every application of note. Icwas the automation of mammoth collections of data and the commen- J
surate ability to sort, search, and maintain those records that led tu the Iadvancement, at breakneck speed, of the powerful computer hardwartr,z:j;
that has become common today. Data is power, and organizationshav+
come to recognize that the ability to harness these information .;
resources is not only a competitive edge, but critical to their survival.
Initially modeled after the hierarchical structure of the paper files that -it replaced, the computerized database has been through numerous
L
&
,%&
incarnations in a search for the most efficient method of maintaining ,.I+$**
the integrity and efficiency of the data sets. In the 1970s Dr. E.ECodd
proposed a database model based on mathematical objects known as ::sjrelations and the processes that can be applied to them. This intellec-
3;;
tual treatise became known as the Relational Database Model, and ithas revolutionized the design and development of data management _,.
,~.i
software. I.
Delphi, with its tight binding to the Borland Database Engine, allows ,$r
the developer unprecedented freedom in the design and creation ot
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
2/347
software that works with database resources on nearly all platforms.This freedom, however, comes at a heavy cost. To reap the benefits ofthis powerful environment, it is up to the developer to create a designthat combines the beneficial aspects of the freedom with the disciplineof the relational model. Before diving headlong into the nuts and boltsof Delphi coding, it is important for you to form a solid foundation ofknowledge in the theory and reasoning that drive this specialized areaof programming. Database development is easy to do and even easierto do badly. The first three chapters of this book are designed to pro-vide you with the background skills needed to make effective designchoices, decisions that let your software derive the maximum benefits
from the wide variety of tools and implementation choices provided byBorland.
The Relational Model
The initial step to take in this foray is to establish clearly what the rela-tional model is. Based on the certainty of mathematics, the definingrules for the relational model describe a system that provides consistentand accurate results in all conditions while maintaining the integrity ofthe data elements as a highest priority An important note to make atthis point is that the relational model is not a blueprint for the physicalimplementation of data storage. How closely a particular vendorchooses to apply the rules is up to them. The RDBMSs (Relational Data-base Management System) and development tools available varywidely in the measure of how closely they are bound to the relational
rules in their efforts to generate greater performance from their storageand retrieval mechanisms. Delphi, as a development tool, and theBorland Database Engine (BDE) in particular, allow a great deal of free-dom in how a database is built using the product. Understanding therules of the road that follow will allow your efforts to benefit from thedata integrity offered by the relational model and the internal power ofthe physical engine driving your database.
What is a Database?
The term database has been applied in a number of different ways,many specific to the development context in which the word is men-tioned. Ignoring the marketing driven terminology for the moment, adatabase is best described as simply a collection of related data. Therelationship is defined by some natural or forced affinity between the
items, or records, that make up the collection. Figure1.1
shows a file of
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
3/347
figure 1.1
The paper file
system was
emulated in
the first data-
base systems.
Figure I.2
The FRIENDS
f/at file
database
I NVOI CE 1098
I NVOI CE1322
I NVOI CE1779
Chapter I -Introduction t o the Relational Database/
, ielm,.
i
invoices, all related by what they represent and the shared informati4
contained within each invoice.
A computerized database is an elec-
tronic representation of this file. It is a.%repository for electronically storing
da1
records, each record being a set of theindividual data elements that describeeach item that the records are
mode&
upon.
The simplest form of a computerized,database is a single file that contains.&.-.of the data. Similar to a paper file con-?taining all of the records, there are
=
certain actions that will commonly beperformed with the file:
*;
.,:
n Adding new, empty records to the database .,-,
_;
.
H Inserting records into a specific position within the database
w Deleting unneeded records
n Retrieving specific records from the database
n Modifying the records contained in the database
The flat file database in Figure 1.2 contains the names of our friends. :+
.:g
FRIENDS
Geur i i Sharon 722 Boston Ln 909 221- 4456
Rol l i ns Hank PO Box 89 818 986- 2091
Geuri i Tom 722 Boston Ln 909 221- 4456
Wayne Mari on Warhawk Dr 303 458- 8095
\
Each record in this table contains one entry about each of the peo@eYj
that we know. Despite the advantages provided by its simplicity, the fkfile poses a number of different problems for the developer and useralike. For example, because all instances of a friend must be con-
;,,*t
;
tained in a single file, the possibility of update anomalies affecting the
integrity of the data is great. Notice that two records are needed to ,G
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
4/347
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
5/347
Columns
Chapter I Introduction to the Relational Database( ,s*s*Y
are Single V a l u e d
This first property is of primary importance, as it sets the stage for
many of the later properties and methods of the relational database.This rule implies that there are no repeating groups in the table, a.$
:s
repeating group being duplicate entries in the table representing the ;z?
j
same entity. The power, flexibility, and integrity of the relational data- :i;base model are derived from the strict application of this standard.
.
;.$_.
,*~~m
to expect that there may be some duplication among the value&non-key columns of the resulting table. The project operation iunique values in the new table.
Product
The product operation puts two rows from separate tablesto&the resultant table. The new relation is now twice the column 1the original base tables.
Ioin
The join operation combines the Product and Select operationsduce the new relation. Rather than simply combining the columitwo tables, the rows to be combined are defined through the Qa Select operation.
Union
The union operation vertically combines the data in the rows of8relation with the rows in another table. removinn duDlicate rresulting table. Vertical combination requires that the columnsfor each of the base tables be defined exactly alike.
intersection
The intersection of two tables is a relation containing those row
are common to both tables. The intersection operator evaluatescontents of matching columns in each table to determine if theare a match.
Difference
The difieerence of two tables is a relation that contains those rowsexist in one of the two tables but not the other. The unique rows
each relation are selected after a comparison of column values
Division
The division operator results in a relation that contains colufrom one table for which there are other matching columnsponding to every row in another table. In other words, a rgoing to be divided by another relation with the quotient brelation. Consider the example shown in Figure 1.7. Dividing the T
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
12/347
INGREDIENT relation by the RECIPE relation results in a new RThe resulting table answers the question: Who can provide all Or -, ,,ingredients for this recipe?
JS
.ti,
i;r ,.
,,
SUPPLIERS TI-A/
100
200
300
100
Kingfish, Inc.
Kingfish, Inc.
The Crab Walk
33 c
4 T
c 2 2
Crab
Tuna
Crab
Devil Ray Foods CRXXI Crab
Kingfish. Inc. v 3 Onion
3 0 0
k
2 0 0
3 0 0
RECIPE
Devil Ray Foods V G X X 9 Onion I
The Crab Walk BR Bread Cr
Devil Ray Foods 1Fuo
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
13/347
Chapter 2 discusses the practice of designing the relational database. -;
Careful design, as in all software projects, pays off in the measure of ,.integrity and performance evident in the final database.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
14/347
Included i n T h i s C h a p t e r :
H Diagramming the Database 4 Case Study 8 Nor-malization n Normalization Case Study n Translating a
the Logical Design into a Physical Design
As with any programming effort, taking the time to plan and createa.1
proper design pays off when the rubber hits the road and the timecorr
*
to develop a database application. The application creation process is 1L-a
simplified, as numerous problems and issues have already been
g
addressed up front, before the first Begin statement is coded. If youdont
care to spend the time to carefully consider your database up front, you
can simply pay the price in stability, accuracy, and programming effortneeded to make it right on the back end.
Logical database modeling, the subject of this chapter, is very similar tothe practice of object modeling; in both processes you are attempting to
28
identify the real-life items, relationships, and processes that youre goingto emulate with your software. The model that we create is going to _p.d
-%z
meet all of the requirements of the relational database model discussedin the preceding chapter, and because of that, it will reap all of the bene-fits. There are going to be three areas of activity described, and in the .i
course of examining them, we will become familiar with the Redwood
Fish Foods Company, our case study.F
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
15/347
Chapter 2-Logical and Physical Database Design
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
16/347
_---.
Relationsh
Figur e 2. I
Cardinality of
relationships
Chapter 2-Logical and Physical Database Design, .- F _ (_ ..-> -_
I
-.
_
.i-
.i -_I;_.d-,
.. s I.. __=n _ -v_e
that describe the object. For example, a VENDOR will have a name,::street address, and city attributes that serve to make that instance (VENDOR different from all the rest. Attributes should be simple, disgCrete pieces of data such as the city or state, atomic in nature, mea&
that they describe only one element of the object.1
r
ips
I
Relationships are the linking agents between the identified entities.d
the case of two entities, VENDOR and ITEMS, we can identify a rel&? $tionship as supplies, as in the VENDOR supplies ITEMS. Thrt:ebrcategories, generally described by verbs or prepositions, are generalindicators of the existence of a relationship:
w Existence relationship-a VENDOR has EMPLOYEES
w Functional relationship-an EMPLOYEE fi&Hs ORDERS
n Event relationship-a VENDOR delivers ITEMS
The entity-relationship diagram displayed in Figure 2.1 demonstratd _ _pronertv of the defined relationships; each has a cardinalin/. .i
One-to-One I : I
INVOICE LINE ITEMS
One-to-Many I :M
PARTS
PRoDUCTSl-----l
I
Many-to-Many M:M
Cardinality
is the number of expected occurrences of the relationshipbetween two entities. A one-to-one relationship means that for eachrecord (set of attributes) in the first entity, there is exactly one
.7aa
-j
,A
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
17/347
22 n Part I--TheRelational o t a b a s e _ _
occurrence of a related record in other entity in the relationship. In Fig-ure 2.1, the first example says that for each instance of WAREHOUSEthere is exactly one WAREHOUSE MANAGER.
rip
There are many accepted methods for the graphical representa-
tion of an entity-relationship diagram. For purposes of simplicity,
we are going to document the cardinality degree of our relation-
ships with one of two symbols. One-to-one relationships will be
denoted with a single arrowhead(-+).
Relationships with multiple
cardinality will be shown with two arrowheads on the relation-
ship line ++).
The second example, a one-to-many cardinality, is demonstrated by theinvoice to line items relationship. In this relationship, one record in thefirst entity is related to one or more records in the other entity. Theexample diagrams a relationship in which each INVOICE contains oneor more LINE ITEMS.
The last relationship in the example is the most complex. Amany-to-many cardinality represents that one or more records of one of
the entities has relationships with one or more records of the otherentity. The many-to-many relationship is difficult to diagram and evenmore difficult to translate into a logical and physical database design.The recommended course for handling relationships of this type is thatthey be further decomposed, if possible, into a pair of one-to-manyrelationships. Figure 2.2 is an example of this process.
The original relationship had two programmer entities assigned to oneor more of the project entities. Creating a new entity called TASKS and
then establishing two one-to-many relationships between the relationscreates a clearer representation of the relationship. The first, betweenTASKS and PROGRAMMERS, states that one PROGRAMMER is assignedto one or more TASKS. A second relationship is then established thatsays that the PROJECT entity has one or more PROGRAMMER entitiesassigned to it. No information is lost in this process and you end upwith a much more understandable design.
Chaster 2-Logical and Physical Database Design
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
18/347
Figure 2.2
Amany-
to-many
relationship
decomposed
Primary Keys
g y g.__.**~
PROGRAMMER /
JO+ Yp,,,
P R O J E C T Y
1
TASKS
I
,t,
Relationships also have direction, unlike some of the programmers. Thedirection of the relationship describes which entity is the from entityand which is the to. The from is also referred to as the parent whilethe to entity takes the label of child. The direction of a one-to-onerelationship is for the most part arbitrary. A one-to-many cardinality
requires a little more thought to discover the direction, although oftenthe verb or preposition that describes the relationship provides a strongindicator. For example, an INVOICE has LINE ITEMS; the INVOICEentitv has the LINE ITEMS, making it the oarent to the LINE ITEMSchild.
The singular nature of items in a relational database system is the keyconcept that drives the paradigm. By ensuring that each record isunique in some way, the results of either a query or data manipulation
c
,;
operation can be guaranteed to be correct by the database system. A . :primary key is an attribute value on which the non-redundancy rules .are heavily enforced. Though attributes in the remainder of the record
r
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
19/347
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
20/347
26n f rt -The Relational Database
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
21/347
The customers area code must be equal to 303 or 719 or ,-.
720 or 970.: f
I
Each attribute in every table should be reviewed with the user to deter-$mine the constraints necessary for maintaining the integrity of the data.Gg
Acceptable ranges of data as well as format and type are all items that I?$work together to implement a business rule. The rules will become a t?
part of the physical database implementation, either directly imple- :$
mented through the data structure or handled by the supporting code. 2;r;
There is a second aspect of the rules that needs to be discussed, theissue of triggering. Business rules become a part of the field definition
1:
ii;
for each relation. Obedience to the rule is tested during specific opera- ;tions on the database. These actions are called triggering operations.
.-I
Three database operations trigger the business rules tests:-.
l Adding data to a database*
*
m Deleting data from a database.:I
w
Updating the data in fields of a database *.-
Triggering operations cause the relational system to validate that the ~.;database is being changed according to the rules defined for the partic- 3ular field. For example, when adding a record to the SERVICE CALL 21
table, the data being entered for the Area Code field is validatedagainst the four acceptable codes that were defined. Entering 415would generate an exception and the RDBMS control mechanismswould prevent the user from entering this data.
Likewise, a deletion operation should trigger a more complex validationprocedure. Take the example of an INVOICES table that draws the ven- I jidors address from the VENDOR table. A business rule applicable to this :J
situation is: Every vendor ID that appears on an invoice must be a verifk .d
able and valid vendor ID. . j
.G
a :
This indicates that as long as open invoices contain a vendors ID num- $iber, there must be a record in the VENDOR table that matches that ID.
.
If the user tries to delete a vendor from the VENDOR table, a validation --procedure must examine all open invoices to determine if that ID is stillin use. If it is, an exception must be raised to alert the user to that fact -:i
and prevent her from removing the record.
,_- - i~--4- n.i_- -
Chap te r 2-Logical
and Physica l Datab aseDesigrp
._j.j
v
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
22/347
Case Stu
The Player
Figure 2.4
The en ti t ies of
the RedwoodFish Foods
Company
dY
The best way to apply these conceptual tools is to work our way :
through an example. To do this well examine a common database LB
application, the order entry system. This business model is easy to .S
understand: A company sells items to customers. The customersthe company and provide their name and address and payment imation, which the company retains for future reference. The custdselects the items that they would like to purchase and orders thecompany, in turn, pulls the item from inventory, prepares an inthe offsetting entry to the customers payment, and ships the itdors ship the items to us that we sell to the customers. The ReFish Foods Company will be the company that opens its doors to
exploration.
l S
In this example, it is relatively easy to pick out the entities. Remethat the entities are those people, places, or things about which we4want to record facts in the database. Figure 2.4 collects theidententities for Redwood Fish Foods and, as shown, we will be using
standard rectannular remesentation of an entitv in all of the dia
CUSTOMERS
I N V O I C E S C REDITTERMS Iii
Five entities were identified from the case description:
n Vendors
n Customers
H Items
n Invoices
w
Credit terms
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
23/347
Chapter 2-Logical and Physical Dcrtabase Design n.va-ilw. _willnsl ._ . , =,,>a,_ -q
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
24/347
I Can Relat
the fields in the VENDOR entity could stand a reasonable chance ofbeing the primary key. In one way or another, each of them could be .,Iexpected to be unique in each record. As we review them, lets firstconsider if any of the values of the attributes is likely to change as the 1:database is put to use. Primary key fields should be the most stable iIi I
the database since so many items are linked by and through them. TheStreet, City, State, Zip-Code, Telephone, Fax, and Contact fields coulft- c 1not become a part of the filename. Ifyour application needs to use a configuration file other than thedefault, it can call the BDE API function DbiInit to initiate the processand point to the other file. If another application is running using thedefault file and this action is attempted, an exception will be raised.
The Windows Registry contains information regarding the drivers, vari-ous pieces of system information, and the size of the Buffer Managercache. Information that is stored in the configuration file includes thecurrent NET DIR entry for Paradox tables and all alias information.
Base configuration changes can be made through the BDE Administra-tor. The engine is configured through changes made on theConfiguration tab of the Administrator. Option categories availableinclude:
nINIT
n Date Formats
n Time Formats
n Number Formats
The system INIT settings are the initialization options used when start-ing an application. All of this information is stored in the registryFigure 4.5 is a table showing the parameters accessible through theINIT branch.
lapter 4 -The Borland Database Endne and the Database Utilities q -
AUTO ODBC
DATA REPOSITORY
Determines if the ODBC drivers and data soup
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
75/347
DarteFo rma ts
DEFAULT DRIVER
LANGDRlVER
LOCAL SHARE
LOW MEMORY USAGE
LIMIT
MAXBUFSIZE
MAXFILEHANDLES
MEMSIZE
MlNBUFSiZE
MTS POOLING
SHAREDMEMLOCATION
SHAREDMEMSIZE
SQLQRYMODE
SYSFIAGS
VERSION
I If the table name provided ha s no extension or t~c~::r
TYPE is of FILE, this is the driver that is tried first,,
e driver matching the version I
ascii ANSI (DBWlNUSO)
shared between BDE
applications at the same time.
The maximum amount of lowmemory that tne
Th
e maximu
cache.
When True, MTS pooling is enabled. This improvua
the initial opening-time of a database.
Th is determines the preferred address of shared
memory manager and shared buffer mana]
This is the maximum amount of memory that the
BDE will utilize for shared resources.
The selected method for handling queries todata sources.
Do not modify.
] Do not modify
Figure 4.5 The IN/T options accessible through the BDE Administrator
The options in the FORMATS DATE branch of the configuration optionmodify the handling of data strings in BDE applications. The
parame
~l
ters surfaced here, shown in Figure 4.6, affect the way in which string :values are converted into date values.
FOURDIGITYEAR
LEADINGZEROD
LEADINGZEROM
84 n Part //-The Delph i Database Tools
WhenTrue,
all year values are expressed in four
digits.
When True, single-digit days (I ..9) contain a leading
zero.
When True, single-digit months (I..9)
contain a
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
76/347
MODE
leading zero.
This controls the order of the month, day, and year
components of a date.
0 - MMDDYY
I - DDMMYY
2 -WMMDD
SEPARATOR
YEARBIASED
Defaults to the order used by the country selected
in the Windows Control Panel.
This is the separator character used to demarcate
the month, day, and year components of a date.
This parameter determines whether or not the
BDE application will add I900to two-digit years.
figure 4.6 The date format options accessible through the BDEAdministrator
Time FormatsThe parameters accessible through the FORMATS 1TIME branch deter-mine how string values are converted into time values acceptable to theBDE. The parameters are listed in Figure 4.7.
AMSTRlNG
MILSECONDS
PMSTRlNG
SECONDS
TWELVEHOUR
This is the string used to indicate morning. It defaults to
AM.
When True, time values include a millisecondscomponent.
This is the string used to indicate evening. It defaults to
PM.
When True. time values include a seconds comp onen t.
When True, a I2-hour clock is used to express time
val ues. When False, a 24-hour clock is utilized. I
Figure 4.7The time format options accessible through the BDE Administrator
Chapter 4-The Borland Database Engine and the Database Util i t ies n 85
Numer ic Fo rma ts
Much as the TIME and DATE format parameters control the string con-version into time and date values, the NUMBER parameters determinehow string values are converted into numeric values. Figure 4.8 liststhe parameters accessible.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
77/347
e maximum
number of decimal places in the string converted
numeric values less than I have
at-ate the thousands components of large
Figure 4.8 The number format options accessible through the BDE Adminis tra-
t or
The Database DesktopThe Database Desktop is a utility that ships with the Borland DatabaseEngine and gives the developer the ability to create, delete, modify, andquery database files. It supports the standard driver databases: Para-dox, dBASE, and some SQL implementations. In fact, the trained eyewill recognize the Database Desktop for what it is, a reduced functionversion of the Paradox database.
Creating Tables
One of the most common uses for the Database Desktop is creatingtables for use in your Delphi projects. The Database Desktop can createa wide variety of table types. Depending on the type of table that you
\
choose to build, a varying array of capabilities will be available for themodification of the table. Aside from naming the columns and definingthe constraining sizes and data types, you may also find the ability to:
H
Specify a table language to control sort order and the available char-acter set.
n Assign columns for indexes.
w
Use (borrow) the structure of another table to create a new one.
I Assign the primary key for a relation.
Create secondary indexes for a table.
n Define domain constraints for the columns of a relation.
n Establish relationships between tables.
n
S t th it t i t f t bl
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
78/347
Set the security constraints for a table.To demonstrate the range of options ava ilable through this method oflable through this method of
/
establishing tables, we will build a sample Paradox table to be used in ain a
Delphi project. The table will make use of the Paradox validity checkfeatures to bind the domain constraints to the table. The ti - -l will rep-l will rep- Iresent basic registration information for an elementary school student. i
Start the Database Desktop program to begin the process.
I. Select File 1New from the menu. The Create Table dialog will be dis-will be dis-
played, allowing you to choose the base format for your table. For thisexercise, we will use the default type of Paradox 7 as shown below.
Figure 4.9The CreateTable dialog
2. When the file type is selected, you will be presented with the CreateParadox 7 Table dialog as shown in Figure 4.10. This is where allmemaining design work on the table will occur.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
79/347
3. Figure 4.11 contains the schema for the REGISTER table that we arecreating. It describes the field name, data type and size, and domainconstraints for each column in the table.
SOCIAL I IIRI-I-V Ml
IM
Createall
1STREET
STATE Default value to CO.
ZIPZIP AA 55 Required field. The value must equalRequired field. The value must equal
80439 to ensure that the student lives80439 to ensure that the student lives
in the district.in the district.
Figure 4 I IFigure 4 I I The schema of the Register t b eThe schema of the Register t b e
4.4 . Begin by entering the name of the first field, Social Security Num.Begin by entering the name of the first field, Social Security Num.Tab to the Type column and select a data type. Pressing the space barTab to the Type column and select a data type. Pressing the space barwill drop down a list of possible data types supported for the databasewill drop down a list of possible data types supported for the databasetype. For this field, use the Alpha data type. Tab again and enter 11type. For this field, use the Alpha data type. Tab again and enter 11for the field size. Finally, this field is the primary key for the table sofor the field size. Finally, this field is the primary key for the table so
88 Part I/ The Delphi Databose Tools
this must be indicated in the Key column. Press any key to mark thisas the primary key. Your design should appear as shown below.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
80/347
Figure 4. I2Adding infor-mat i on r t he
Soci al Securi tyNurn f i e l d to
tabl e
5, You will now set the domain constraints for this column. The only con-straint for this field is that it is required, being the primary key Toindicate this in the Paradox .VAL (validity check) file, click on theRequired Field check box. Add the Last Name and First Name fields inthis same way.
6 . Add the Date of Birth column to the table. The validity check value forthis column requires a little more work, The constraint requirements
for this field state that the child being registered must be five years oldor older on the first day of school. For this exercise we will establishthe first day of school as September 1, 1999. Therefore, to be oldenough, a childs birthday must be prior to or equal to August 31,1994. Implementing this constraint in a Paradox table utilizes a Maxi-mum value validity check. For this school year all children should havebeen born no later than August 31, 1994. This constraint is shown inFigure 4.13.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
81/347
7. To simplify the data entry process, another validity check that can beadded is a default value. For this database, the vast majority of entrieswill come from a single town and state. When the column City isentered, add the value Evergreen (minus the quotes) to the Defaultvalue field. Perform the same operation for the State Column, entering
CO as the default value. When an empty row is added to the data-base, these values will have already been entered.
8 . Finally, add the Zip column. As a further verification of the studentsdistrict status, the zip code should be validated. A narrow range of val-ues, sometimes as low as one, can be used to validate an entry For theZip column, the highest and lowest value that should be allowed inthis field is 80439. Setting this validity check is simply a matter ofentering this value in both the Maximum value and Minimum value
fields of the validity check.9. Save the table with an appropriate name in the work directory for
your application. Remember that an alias will be needed to locate thetable for use in Delphi.
Using the Database Desktop, you can immediately test the results ofyour modifications. Open the
RFGISTER
table and click on the EditData button to open the table for data entry Experiment with an entry
to see the errors that are generated when incorrect values are entered.The messages till appear in the desktops status bar. The validitychecks you created will prevent poor quality data from being added tothe database. These same validity checks will raise exceptions in your
Delphi code, making it much easier to trap errors in the data input byyour users.
Another benefit of using the Database Desktop for table creation is theability to add Picture clauses to each column, helping you to format thedata in the most presentable manner. For example, you can modify the
presentation of the column that contains the Social Security number soth t t i i th t d f t f T dd
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
82/347
I.
2.
3.
presentation of the column that contains the Social Security number sothat entries appear in the accepted format of - - . To addthis picture string using the desktop:
Select File 1Open 1Table from the menu and navigate to the aliasunder which you saved the REGISTER table. Open the table.
Click on the Restructure button, opening the Restructure Paradoxtable dialog. This will contain the current structure of the REGISTERtable. Alternately, you can get to this point by selecting Tools 1Util-ities 1Restructure and then selecting the table.
Select the Social Security Num column. Click on the Assist buttonbelow the Picture field. This opens a dialog that helps you to formatthe picture appropriately or allows you to experiment with differentformatting strings. Figure 4.14 is the Picture Assistance dialog. In thePicture field, the string *3{ )-*2{ )-*4( } represents the standard-ized format for a Social Security number.
Figure 4.I4
The Picture
Assi stance
dialog
The chart in Figure 4.15 shows the recognized picture string characters.These characters are substitutes for the data that will be entered intothe field. The formatting is positional, meaning the character that isinput in a particular location is formatted according to the picturestring character found in that spot. Any characters other than those
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
83/347
92
n Part I/-The Delphi Database Tools
builder knows which files from the BDE can be distributed per thelicense granted by Inprise. You cannot use your Delphi installation diskto install the BDE on a client machine. During the development of theinstallation script, the installation program will determine if you wantto perform a complete or partial redistribution of the BDE.
Borlands reasons for this requirement are sound even beyond simple
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
84/347
Borland s reasons for this requirement are sound, even beyond simpleprotection of their property Careless installation of the Borland Data-base Engine can easily cause other programs to fail. Remember theearlier mention of the number of applications that utilize the BDE fortheir core database functionality An installation of a later numberedversion of the BDE can overwrite or otherwise destroy references to theother installations of the engine, effectively destroying the other appli-
cations database access. Use of a certified installation programprevents these entries from intersecting. Inprise now also includes a.CAB file for distribution with ActiveX controls.
The only BDE utility that can be distributed with an end user applica-tion is the BDE Administrator, and it is included with a certifieddistribution as outlined above. None of the other utilities, including theDatabase Desktop and the Database Explorer, are redistributable.
Database Explorer
The Database Explorer is a utility shipped with Delphi that incorporatesa hierarchical database browser with data editing capabilities. The util-ity is also the gateway to the creation and manipulation of datadictionaries for Delphi datasets. A data dictionary is a special databasethat contains the attribute sets for field components. The tool ships in
three different flavors with two different names, depending on the ver-sion of Delphi in use. The Desktop and Developer versions of Delphireceive the Database Explorer while the Client/Server version isshipped with the SQL Explorer. Their capabilities differ commensu-rately with the database access capabilities offered with each version.The Database Explorer that accompanies the Desktop edition accesseslocal databases only, while the Developer edition gains access to theLocal Interbase Server and ODBC-compliant databases. In addition, the
data dictionary is enabled. The Client/Server version of Delphi shipswith the SQL Explorer, giving the developer extended capabilities wit&access to a full range of SQL databases, both local and remote.
Chap te r I-The Bor land Database Engine an d the Database Utilities n 93
fbtabase Explorer Interface
The appearance of the Explorer closely matches the format seen in theBDE Administrator. Figure 4.16 shows the dual-paned window used forall actions in the Explorer. The left pane contains two tabs: the Data-bases tab listing all database aliases defined to the BDE and the
Dictionary tab showing the contents of the data dictionaries that haveb d fi d
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
85/347
been defined.
:.
T F we 4 . 1 6
; Th e Database
T
q DBDEMOS-- i DddtDD
The contents of the right-hand pane vary according to the objectselected in the left-hand pane. The number of tabs and their descrip-
tions will change with the choice of more detailed selections. Statusbars are displayed above each of the panes, giving you a summarydescription of what you are currently viewing.
The hierarchical viewing capabilities are constrained to the left pane. Inthis window, the developer can drill down to increasingly detailed lev-els of information about the database selected. In Figure 4.17, theDBBDEMOS database has been expanded from the root of the hierar-
chy by clicking on the plus sign next to the name. When a database isselected, the detail in the right pane will be the alias informationdefined when it was established. As shown, the next items listed are thetables that make up this database. Each of the tables is also prefacedwith a plus sign, indicating that there is further detail about each ofthem available.
II
H
94 HPart I I-Th e Delphi Database Tools
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
86/347
Figure 4.I7
The hierarchi-
cal view of the
Explorers
Oatabases tab
The detail for the REGISTER table, built earlier in this chapter, hasbeen expanded. The number and names of the nodes that appear willdiffer for each of the supported table types. The Fields node in theexample is expanded to show all of the fields that were defined for thetable. Selecting the field narrows the information down to the field def-inition. Information also available for the Paradox table includes theIndices, Validity Checks, Referential Constraints, Security Specifica-tions, and Family Members. Perhaps most importantly, the data that thetable contains can be modified and examined.
The Database Explorer can also be used to establish a new alias. The
methodology is the same as that used for the BDE Administrator.
Data Dictionary
The ability to create and utilize a data dictionary is a distinct advantageof the BDE/Delphi development tool. A data dictionary is a databasethat is used to store attribute sets for field components. Attribute sets
determine the field type, properties, and the data-aware componentthat should be generated whenever a TField object is dragged to a formfrom the Fields Editor. A data dictionary containing an attribute setmeans that you will only need to set properties once to have thempropagated throughout your project.
rhapter
I---The B o r l a n d Database En gin e an d the D a ta b a s e U ti li ti es q
95
This tool displays its use when you have several columns in a databasethat share common formatting properties. An extended attribute setcan be set once for such things as the alignment, picture string, andminimum and maximum values, and then be associated with multiplefields in your application. If a change is necessary it can be made oncethrough the Explorer and it will then flow to all of the components that
use it at once.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
87/347
Elgure 4.18
lnfirmation fir
I-
0new dictio-
$wfyin
the
4Create a New
XcGonafy
I..
3 .
-
r...
Attribute sets can be changed both through the Database Explorer andthe Fields Editor. The editor will be discussed in conjunction with thecomponents it services in a later chapter; right now we will focus oncreating an attribute set through the Explorer. The first thing to bedone is to create a new dictionary Start the Database Explorer, eitherfrom the Start menu or from within Delphi, using the Tools menu.
Select the Dictionary tab in the left-hand pane.
Bight-click on the Dictionary entry and select New. Alternately, youmay select New from the Object menu. The dialog shown in Figure4.18 will be displayed.
Enter the data shown in the example dialog. The Description field isoptional. Click OK to save the new dictionary.
You can create multiple dictionaries as needed to support your develop-ment needs. Only one dictionary is displayed at a time; the DatabaseExplorer does not extend its hierarchical display to this feature. Towork with alternate dictionaries, select Dictionary 1Select from themenu and choose the dictionary name from the drop-down box.
Establishing the attribute sets that make up the contents of the new dic-tionary is the next step. Attribute sets can be created manually orimported from databases or SQL constraint sets. Before establishing anattribute set, it is helpful to view an exceptional example provided byBorland. This dictionary is linked to the examples provided with theDelphi package so they must be installed prior to exploring this item.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
88/347
Chapter 4 Th e Bo r l and Da tabaseEngineand
th e Database Uti l i t ies 97
DisplayLabel
DisplayWidth
ReadOnly
When the field is displayed in a grid control, the field name is
the default column heading. The entry in this parameter
replaces the default value.
This determines the number of characters used to display a
field in a grid control.
This determines if a field can be edited or if it is read only.
Values are True/False
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
89/347
Required
Visible
Transliterate
EditMask
DisplayFormat
EditFormat
MinValue
MaxValue
Currency
Precision
DisplayValues
BlobType
DefaultExpression
CustomConstraint
Error String
Based On
~ : - :,
Values are True/False.
This determines if the field requires an entry. Values are
True/False.
This determines whether or not a field can be displayed in a
grid control. Values are True/False.
This determines whether or not a field type is translated
between types in different databases. Values areTme/False.
This value contains the Edit mask, the formatting character
string that determines how data can be entered into an edit
bOX.
The value in this field determines how the field value is
disolaved.
This determines how numeric values appear when edited in
a data-aware control.
This sets a minimum allowable value for the field.
This sets a maximum allowable value for the field.
When set to True, this indicates that the values entered in
this field are currency values.
This determines the number of decimal positions that are
formatted prior to being rounded off.
This determines the translation of values in a Tboolean field
to and from the display format.
This field specifies the type of blob associated with a memo
or graphic control.
This specifies a default SQL value for the field when it is left
empty during data entry.
This specifies a SQL string that enforces a value constraint
on the field.
This determines the custom message that is displayed when
theCustomConstraint
is violated.
This specifies a different attribute set from which the
current set is based. The settings in the current set override
the or iginals.
Figure 4.20 Extended attributes for the TField objects
98 n Purt I I-Th e Delphi Database Tools
The entry for the field VendorNo contains some interesting examples ofthe level of control that can be exercised through the data dictionary.
Note first the DisplayFormat. The entry contains the value VN 0000,which translates into a literal string of 70-J followed by the vendornumber that you want to assign. It is important to remember that this
differs from the EditFormat entry, especially when you are enteringdata. When a new value is entered for the vendor number, the VNill t til ft th l i t d
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
90/347
will not appear until after the value is accepted.
The value acceptable for this field is constrained by theCustomConstraint SQL string. This field contains any valid SQL stringthat you wish to use to validate or otherwise constrain the data for thisfield. Values entered that violate this constraint will cause an exceptionto be raised. When the exception occurs, the error message containedin the Error String field is displayed, overriding the default exceptionmessage.
Below the entry for the VendorNo field are two more nodes. Expandingthe Referencing Fields node demonstrates the usefulness of the datadictionary Notice that two fields in entirely separate tables referencethe extended attributes set for the vendor number. By setting theparameters for a field once, we are able to reuse the attribute set for
any similar field. Whether the data item is the same, as is the case withthe vendor number, or different data items with similar formatting, asingle entry in the data dictionary can format multiple fields. When thesettings need to be modified, expanding the range of allowable valuesfor the vendor number for example, the modification is made at a sin-gle point rather than at each field in the database. This saves enormoustime and makes for much cleaner code.
The REGISTER database is a comfortable place to establish our firstattribute set. The attributes that are going to be set will be used for ver-ification of the Date of Birth field (renamed DOB for simplicitys sake).After reopening the dictionary DemoDictionary created earlier in thischapter, follow these initial steps to establish a new attribute set:
I. Expand the nodes of the dictionary by clicking on the plus sign. Youshould have two empty nodes: Databases and Attribute Sets.
2. Right-click on the Attribute Sets node and select New from the con-text menu. A new attribute set called EXTFIELDl will be opened.
3 . While the set name is highlighted, rename it DOBField.
4 . Three items in the attribute set are going to be modified for this field.Figure 4.21 is the right-hand pane of the Database Explorer showingthe completed items.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
91/347
1
In order to apply these attributes to a field object, the dictionary mustbe associated directly with the TField object. The project DBTEST(included on the CD) will provide the basis for testing the attribute set
just created.
The main form for the ect is shown in Figure 4.22,
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
92/347
Figure 4.22DatabaseBreadboard
dialog
Invoke the Fields Editor from the Table1 component by double-clickingon it. If the columns of the REGISTER table do not appear in this form,right-click on the Fields Editor to invoke the context menu. From thecontext menu, select Add All Fields, Your next step in utilizing the
attribute set from the dictionary is to associate the definitions with thefields of a table.
I. Click on the DOB field, Notice in the Object Inspector that a differentset of properties has been exposed. These are the TFieid specificproperties.
2 . Right-click on the DOB field and select Associate attributes fromthe context menu The Associate Attributes dialog will appear as
shown in Figure 4.23. The single attribute set that we defined,DOBField, will appear for selection. Click OK.
Figure 4.23The AssociateAttributesdialog
4.
ChapterThe
&w/and
f h t u f m s e
Engine and theDatabuse
UtilitiesW
IO1
3 . The properties in the Object Inspector that relate to the attribute setproperties will now be filled with the parameters from the datadictionary
Close the Fields Editor and compile the project.
Test the project by entering various dates in the DOB field. The error
message defined earlier will appear for each date that fails outside ofthe range. You will also discover that the validity checks set in earliersections are in place For example the row will not be accepted without
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
93/347
sections are in place. For example, the row will not be accepted withouta Social Security number.
One critical caveat must be remembered when updating your attributesets. The changes will not automatically be associated with the TFieldobjects. You must associate the new attribute sets with the objects andrecompile your project before the changes will appear in the execut-able-a small price to pay for the flexibility offered through a datadictionary
The Dictionary Menu
The Dictionary option available on the main menu provides access to anumber of different functions pertaining to the management of data
dictionaries.paragraphs.
Select
As discussed
Each of the selections is detailed in the following
and utilized earlier, the Select option is used to select anexisting data dictionary from the Select a Dictionary dialog.
Register
The Register option is utilized to register a new data dictionary in theObject Repository, making it available for selection. The Register anExisting Dictionary dialog box appears when this command is issued.You can then provide details about the dictionary to be registered.
Unr egister
Unregister removes the registration of a data dictionary in the ObjectRepository The dictionary itself is not affected by this command; it willsimply not appear in the Select a Dictionary dialog.
102 Part H The Delph i Database Tools
New
The New option is used to create a new dictionary As seen earlier, adialog box requesting the details of the new dictionary is displayed.
Delete
The Delete option is a destructive command that will delete the speci-fied data dictionary file. The deletion is performed through the Delete a
(
;:
,
._
-.,
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
94/347
y p gDictionary dialog box.
Import from Dutabase
The Import from Database option allows you to import table schemainformation from an existing database into a new or updated data dic-
tionary The dialog box that appears, Import Database, is used todetermine the column attributes that you want to import into the datadictionary as attribute sets.
Import from File
Similar to the previous command, the Import from File option importstable schema information. This command works with information con-
tained in a flat file rather than a data-dictionary file format. The flatfile format that it recognizes is the Borland Dictionary Export file exten-sion (.BDX). This type of file is created using the Export to Filecommand from the same menu.
Export to File
This command exports a data dictionary to a flat file format. As
explained above, the flat file can be imported using the Import fromFile command.
importing SQL Cons traints
The Database Explorer can import SQL server-based constraints anddefaults into a data dictionary to be used in Delphi. This action is per-formed through the Import from Database command described earlier.
The constraints that are imported differ by server. Any items that arenot supported by the BDE are commented to prevent errors from beinggenerated.
.i
Chapter he Bodand Database Engine and the Database Utilitiesn 103
Before performing this action, you should be very familiar with the SQLdatabase and the types of constraints that it supports. This informationwill determine where you will find the different types of constraintsafter importing them.
The discussion in this chapter provided a survey of the functionality of
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
95/347
The discussion in this chapter provided a survey of the functionality ofthe core of Delphis database access, the Borland Database Engine. Thedriver-based architecture of the BDE makes it, and your applicationsthat utilize it, infinitely extensible. This design allows the BDE to sup-
port your application needs from the desktop all the way to complexmulti-tier applications supporting a wide variety of SQL databases. The
ODBC socket extends the BDE support to cover nearly every desktopand midrange database currently on the market. The transparency ofthe engine and the low-level requirements of each database type allowthe Delphi developer to concentrate on interface and functionalityissues rather than the database access components of a project.
The Borland Database Engine is not a single executable file but ratheran entire suite of executables, drivers, and utilities. We have covered
the majority of the engine level functionality in this chapter. If yourapplication needs focus on an individual file type, it is recommendedthat you explore further the unique capabilities of that databasethrough the engine documentation.
Looking Forward
The next chapters will finally get into the meat and potatoes of Delphidatabase programming. The data access components will be examinedfirst since they are the ones that actually link the program to the datafiles. Then the data controls are put to work, creating the outstandinginterface that Delphi is famous for.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
96/347
I n c l u d e d i n a h i s Chap t e r :
wThe Dataset Objects n The Table Component (TTable)n The Query Component (TQuery) n The DatasourceComponent (TDataSource)
H Putting the DataSource,Table, and Query Components to Work H The StoredProcedure Component (TStoredProc) n The DatabaseComponent (TDatabase) n The Session Component(TSession) n The BatchMoveComponent (TBatchMoye)n The UpdateSQL Component (TUpdateSQL) H TheNestedTable Component (TNestedTable)
F inally, we arrive at the Delphi promise of RDAD, Rapid DatabaseApplication Development. Dash out a form, slap some components on .__
3
that surface, point the components towards your database, and voil$-ii
a database application is born. Building database applications in Delp&j$$can be that easy but only after spending the requisite time exploring ;the power of the tools. Like everything else in Delphi, the databasecomponents are rich with functionality and adaptability, and the effort:expended to build your knowledge on these classes will result in
ji
2-t?
greater user satisfaction and measurably higher quality in yourapplications.
The data access components, available to the Delphi developer from $the so-named tab of the component palette, are non-visual componenti.that expose the BDE database capabilities to the Delphi development
:f
environment. All database access and manipulation is performed1 cover all of these basethrough these components. This chapter wil
components, their properties, and events.
IO6 n Part II The Delphi Database Tools
The Dataset Objects
^.i
A dataset is the base building block of any database application. The&&
are the objects that contain or access the data; the facts that we am,$attempting to manage. The most immediately familiar dataset
objet+
the table, a structure that we have discussed at length in the prececpages. There are four components on the data access palette that aderived from the TDataSet base class: Table Query Stored
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
97/347
derived from the TDataSet base class: Table, Query, Stored Procand NestedTable. Before examining the individual classes, theing class from which they inherit the majority of their functionabe laid open. .
.-~$
,$
TheDataSet
Object (TDataSet) :
i
The TDataSet object (Latin name, TDataSet) is the core unit that .:*
enables access to tables through the BDE or other database access $
points. A TDataSet object is the ancestor class from which all oth&dataset objects are derived and models such real-life items as a taa database or a query that presents a subset of this data. The clasdefines a set of fields, properties, methods, and events that are initedby all of the descendants. You cannot utilize the TDataSet
ob
directly because many of the properties and methods are virtual ~$2abstract. A virtual method is one that is defined in the base clascan be overridden in descendant classes. An abstract method inclass provides a function prototype but no implementation; descen-
,i
dants are required to provide the implementation. This object modei&
perfect for implementing these database components: Each is built F4$$the cask of accessing data; they just use different methods of
accom-l*
plishing the job.
There are three classes that are direct descendants from TDataSet.TBDEDataSet
enables the TDataSet class to work with the BDE toenable database access (TDataSet itself is database engine indepenent). The TDBDataSet component is a descendant of the DE eniTDataSet that adds additional session and database features.
I~Jx&~
were to develop your own data access components, you would mlikely create a descendant from the TDBDataSet class. The last
cl
also a direct descendant of TDataSet, TClientDataSet. This classdesigned lo implement multi-tier database applications using diuted databases.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
98/347
Many operations, such as setting the current index, also require thatthe
dataset
be closed and reopened for the effects to be seen. Delphiprovides two methods for performing this task as well. The Active prop-erty of the dataset can be set to False at design or run time:
Vendors. Acti ve : = Fal se;
or, you can utilize the Close method of the dataset:
Vendor s. Cl ose;
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
99/347
When the dataset state falls in the open category, the developer mustbe aware of two factors: what actions can be performed against thedatabase and how the dataset arrived at the current state. For example,a dataset object linked to a data-aware control can be displaying the
data but the user may find that he is unable to edit the current record.The developer should be aware that the default state of a dataset,
Browse, will allow browsing of the data values but no modifications.
The state of the dataset will have to be changed to Edit before any
changes can be applied. Depending on the dataset component used,
certain combinations of properties can be set to automatically set the
state to Edit upon accessing the table. Awareness of these conditions isimportant in your design considerations and in testing your application
prior to rollout.
The Table Component Fable
The Table component is generally the first data access control that you
will pair with a DataSource control to construct a database application.
It has been designed to provide uniform access and navigability to each
row in the table types supported by the BDE regardless of the underly-ing rules of the dataset source. Despite the wide range of properties, itcan be quite simple to use. Place a table component on a form, set the
Database and Table properties to point t o the relation you want to
access, and the data flows immediately to your application.
Key Properties
The Object Inspector displays the wide range of properties publishedfor the Table component and the chart in Figure 5.2 provides a brief
definition of each of them. Many of these will be utilized when we
arrive at the first sample application, but there are a number of proper-ties whose values are not self-explanatory or immediately put to use.
Chap te r S--Data Access with Delphi
Active False
Enables or disables cached
AutoCalcFields True
CachedUpdates
Constraints
False
This contains the record-level constraints for
this table.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
100/347
DatabaseName
The name of the database to which this table
belongs.
When True, the data will be ordered by the .Defaultlndex True
False
primary key or index of the table.
Setting this property to True gives the current
application exclusive access to Paradox or
dBASE tables, preventing other users from
Exclusive
FieldDefs
This property contains the field definitions for
the table. This should not be modified unless ..:
you are creating a new table.i
The text string defining the current filtering ,jl:
condition.4.
.3
Filter
Filtered False This activates or deactivates filtering for the
table. ..;
FilterOptions
The set of options affecting the filter process Q
the table.: - ; j
IndexDefs
This set contains information about the
available indexes for this table.
IndexFieldNames
This property lists the column namesfo
be
used in building an index for the table.
IndexFiles
dBASE only. This property specifies index files
IndexName
The property contains the name of a secondary ..
index for the table. I.
The column names from a master table that . 2
links to this child table are contained in this *F
: z
property.
The name of theDataSource
component -:t
linked to the master table in a parent-child ,
relationship.
MasterFields
MasterSource
Name IT h e Internal name of this comoonent.Table I
FalsebjectView
Determines the method of storing the column 3
names. Included for compatibility reasons. : :
ReadOnly
SessionName
StoreDefs
1 False
This determines the read-only status of the
table.
False
Associates a session name with this table.
This property determines whether or not the
Field and Index definitions are stored
1
persistently with the form or data module.
The name of the table associated with this
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
101/347
Aura
TableName
TableType
Tag
UpdateMode
UpdateObject
The name of the table associated with this....
component. r5
ttDefault
This determines the database structure of the 2
table._;
0
0 This property is for the developers use.
UpWhere
This BDE setting determines the method usedAll to locate updated rows.
Specifies the update object used to update a
read-onlydataset.
Figure 5.2 The TTable component properties
Cc Fields
This table property controls the firing of the OnCalcFields event that . $updates the calculated fields in a row. If the property is set to True, cat- %jculated fields will be updated under the following conditions:
;
n The table is opened.
n The state of the table is set to dsEdit.
n ii column is modified through a grid or other data-aware controland the focus changes.
n A row is retrieved from the database.
Depending on the complexity of the calculation and the number of col- $umns with which it works, auto-calculation may slow data entry or ,. :g.-a
retrieval considerably. For this reason, it might be desirable to set this Q
(4
property to False during periods of intense data entry When set to _,::
False, the event will not be fired and the columns will not be updated.
. ,- -
r,iys
Chapter S-Data Acces
~m*b^*s.cI_^*- x1
_-~*_d_j_ij_*s_lyl-_t~*~-~~~~-_*s.__*_*__
Tip
Be sure to fire the OnCalcFields event prior to displaying . ~ ; . i
updated data to the user. Without firing the event, the contents
of the columns will not contain current data. The event does not
need to be fired explicitly; you can also cause one of the triggers
listed above to occur after setting the property of AutoCalcFields
back to True.
CachedUpdates
.:
..f
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
102/347
Another table feature available for improving performance is the ability 3to utilize an internal cache to temporarily store updates to a dataset Jand then write them to the underlying dataset as a single transaction.The CachedUpdates property value determines whether or not the -i,,cache is used. When the value is set to True, the internally cached rows ,,Iwill be updated rather than sending the updates to the remote dataset. -IWhen the default value of False is selected or remains, all modificationsare written directly to the dataset when they are entered. Note that inall situations, client data sets are always cached.
The advantage of caching is in the minimization of traffic to thedataset, increasing the apparent speed of database updates. Using the .cache is not without its drawbacks, however. Without the records or
table being locked, other users can modify the underlying row dataprior to the updates being committed, causing possible anomalies when ,~the current sessions data is written to the table. -9
Enabling CachedUpdates at run time is a matter of setting the Boolean-.
variable:
Vendors. CachedUpdates : = True;
When caching is turned on, the user will work with a local copy of thedata held in memory All updates will be applied to the in-memory dataand written to the source table in a single transaction. Disabling cached 2updates without writing the data back to the table will result in a loss ,iiof data as the updates will be discarded without notification. 1
.;
.$
i
Constraints*
.7
_ ?
Record-level constraints can be set to control the data that can be 4.I;entered in the fields of a table. Constraints at this level of control gen- ,+j
: , s
erally relate one field to another to control the data. , . - +
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
103/347
,
er 5-Data Access with Delphi II113*,x_xH -. >
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
104/347
Figure 5.3
The main win-
dow o f t he
Fi e l dL i n k
Desi gner
The Field Link Designer has done some quick background work and hasalready determined the salient data for you when the program starts.The indexed columns from the detail table have been placed in thedrop-down box; you simply choose the linking field in the detail table
by selecting it from your list of choices. In the example, the column
CustNo has been selected; it then appears in the Detail Fields box.Select this field and move your attention to the Master Fields edit box.To create the linkage, the value in the detail field must match the valuein the master field. Select the CustNo field in the Master Fields box andclick on the Add button. The join will now be displayed in the JoinedFields box. Clicking on OK finishes the process.
,
SessionName
The Borland Database Engine uses a Session object to wrap all of thedatabase connection, drivers, cursor, queries, etc., under a single nameand separate them from other applications use of the engine. Bydefaulr, every database application creates an object called Session andthe BDE maintains a list of all of these objects called Sessions. The
property SessionName allows you to associate a new session name with
n
this table. You will create new session objects only under exceptionalcircumstances, such as concurrent queries against the same database,for two reasons. First, the default Session object can manage a widerange of conditions and needs and rarely needs to be overridden onlow-tier applications. Secondly, the complexity of managing multiplesessions can quickly overwhelm an application and its developer.
Table Type
The property specifies the underlying data table structure for
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
105/347
The TableType property specifies the underlying data-table structure for ,.the table associated with this component. The default value, ttDefault,allows the BDE to determine the table type based on the file extension .: ,7:
that it finds. The associations that will occur with this component are: 3
H DE or no extension-Paradox table
:$
,,i$
w DBF-dBASE table :
n TX-T-ASCII table
This default association can be overridden by explicitly selecting thetable type for your file. The drop-down list offers the following-choices:
H ttDefault-the file extension determines the driver type
w ttparadox-uses the Paradox drivern ttDBase-uses the dBASE driver
H ttFoxPro-uses the FoxPro driver
n ttASCII--uses the ASCII driver. The file is comma delimited, withquoted strings for each field.
b/e Events
The events for dataset objects are somewhat different from those forother visual components. The events are triggered by movement andmodification within the underlying data rather than the changes tocontrol itself. The Table component events are:
H
AfterCancel
n AfterClose
n
AfterDelete
n AfterEdit
W
AfterInsert
n AfterOpen
W
AfterPost
W AfterScroll
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
106/347
Part I/--The Delphi Database Tools.,~~oI _-_- b i lk ,- _ )/
Insert Events
These events fire before the application enters Insert mode and after anew record is inserted.
Open Events
The BeforeOpen event fires when a request to open a dataset isreceived and before the dataset is opened. The AfterOpenevent occursafter the dataset has been opened to the application and prior to anyd t
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
107/347
data access.
Post Events
After changes have been made to a record, the modifications must be
posted to the dataset. The BeforePostevent is fired before the updaterequest is executed. AfterPost is triggered after the changes have been
posted to the dataset but before the dataset is returned to the Browsestate.
Scroll Events
These events fire before the application scrolls from one record to
another and after the scroll action has occurred.
OnCalcFields
The OnCalcFields event fires when an application recalculates calcu-lated fields within a dataset. This action occurs, in the default mode,when a dataset is opened, the dataset is put into Edit mode, the cursormoves from one column or field to another, and when a record is
retrieved from a database.
OnDeleteError
This event fires when your application fails at an attempt to delete arecord. Your event handler can issue corrective instructions and then aretry attempt for the delete action.
OnEciitError
Similar to the previous event, OnEditError will be triggered when anattempt to modify or insert a record raises an exception.
Chapter 5-Data Access wi th Delph i n
.i
.__
_n_ ~qs
OnFilterRecord
?sj
The OnFilterRecord event fires each time a new record becomes the 1- jcurrent record and filtering is enabled. This event handler is included -so that you can set a filter condition that cannot be set in the Filter
..$
property due to its complexity. Each record is tested against this code %&
determine if the data is visible to the application. q4
OnNewRecord
This event is fired when your application adds a new record to the
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
108/347
This event is fired when your application adds a new record to thedataset.
OnPostError
Another of the error handling events, OnPostError is triggered when an ,,;exception is raised by an insert or modification action. L..,..
-*
OnUpdateError
?
.I
The OnUpdateError event is triggered by an exception that is generated:by cached updates being applied to the database. The event handlercan take corrective action based on the error and then request that the
updates be reapplied.
:$
:
OnUPdateRecord
.
This event is fired when cached updates are successfully applied to adataset. The event handler is used to perform more complex updates
~7
than those that can be handled by a simple update action.
The Query Component TQuery)
The Query component is similar in nature to the Table component; itprovides a method of accessing table data from a wide variety ofsources and making it available to the application. What makes it dif-
> ._.I.agerproject :.*--:a> _ . .
5 .5 . To the Current Projects grid, add both a DataSource and Query com-To the Current Projects grid, add both a DataSource and Query com-ponent. The grids DataSource property should be set toponent. The grids DataSource property should be set toDataSource2. The DataSet property of DataSource should beDataSource2. The DataSet property of DataSource should be
pointed to Querya. The Query components DatabaseName propertypointed to Querya. The Query components DatabaseName propertywill be IBLocal and the following SQL statement will be entered forwill be IBLocal and the following SQL statement will be entered forthe SQL property:the SQL property:
SELECT proj - i d, proj -name FROM proj ect
6 . Activate this query to fill the dataset with the results from the SQLstatement.
SELECT proj - i d, proj -name FROM proj ect
6 . Activate this query to fill the dataset with the results from the SQLstatement.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
127/347
ChapterS--Data
Access with Delphi n1
I I. $2
The code for adding a project record is going to be placed in the but- y $tons OnClick event handler. GET-EMP-PROJ has two parameters thag
1s
are going to be gathered from the EMPLOYEE and PROJECT tables. -Enter the following code for the event handler: >.?I
r;
procedure TForml . Buttonl Cl i ck(Sender:TObj ect) ;
begi n
StoredProcl . Prepare;
StoredProcI . ParamByName( PROJ ~I D ) . AsStri ng : =
QueryZ. Fi el dByName( PROJ - I D ) . AsStr i ng;
StoreProcl . ParamByName( EMP-NO ) . AsI nteger : =
Queryl . Fi el dByName( EMP-NO ) . AsI nteger;
StoredProcl . ExecProc;
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
128/347
StoredProcl . ExecProc;
StoredProcl . Unprepare;
end;
12. Compile the program and save it. Execute the application and select a 2programmer and a project. Click the Add Project button and the ,:;ADD-EMP-PROJ procedure will take care of inserting the new row. :When you select the employee record again, the new project will have.
been added to the Assignments list. $2fj. .
The Database Component(TDatabase)
Every Delphi database connection is encapsulated by a Database corn- 1ponent, whether or not you actually place one in your project. TheDatabase component is responsible for providing all of the connection
:
information from the database to your application. An automatically-;;
i;
generated database component is instantiated for each BDE application-;to encapsulate the connection. 5
; ..A
The most important task of the Database component is to provide your 3application with information about the type and location of the data 1files of your database. Recall that in setting up the alias in the BDE, yogfwere required to specify the data location, the driver type, and some -:,g$basic connection parameters. When a temporary database component &$instantiated, these values are read from the BDE and passed to your 13application. This method of obtaining information about the database
connection detracts from the scalability and installation flexibility of
.;-
7the application. For example, to simply specify a new location for thestorage of data files, your users would be required to edit the BDE con--figuration files and modify the parameters of the alias used at the time of installation. This is certainly not the type of task that many users or i7
138 n Part II-The Delphi Database Tools,- . _s ..a.
administrators would be comfortable performing, especially in a corn.plex client/server environment.
A persistent Database component, instantiated when a Database corn-ponent is explicitly present in an application, brings the task ofspecifying the connection information into your application. Databaseconnection parameters can then be stored with your application or inyour applications keys in the Registry, allowing the user enormous flex.ibility in scaling or simply moving an applications data stores. Inaddition, much finer control over transactions and logins is possiblewhen an explicit Database component is added to the application.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
129/347
Key Prr o pe r rties
Since we have left the comfortable confines of the dataset components, db.**athere are a number of new properties that require discussion. The corn-
$i
plete set is detailed in Figure 5.13. ;gj:-y
AliasName
Connected
DatabaseName
False
DriverName
Excluwe False
This determines the BDE alias that djT
The name of the BDE driver for the
Setting this to True enables exclusive
database access, preventing others from
modifying the data.
. ; I
z
Determines whether or not a database -.sz
handle is shared.4-r
_ :;j. . :
Creates a persistent connection even if - ,
the dataset are closed. ...,,~
_ _I
This property controls the display of the -.:.lt:
standardlogin
prompt when connecting .L;:y3
p
to a database.
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
130/347
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
131/347
ea Access with Delphi 14
Somewhat of a letdown after examining all of those exciting properties,there is only one event for the Database component. The OnLoginevent is fired when a login is required by a database. The handler thatyou write provides an alternative method for passing login informationto the server using a more secure source for the username and pass-word information.
Putting ,the Database Comlt>onent to Work
A demonstration of the usefulness of the Database component requiresthat you follow this project with an idea towards improvements that
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
132/347
can be made in your applications. We will start by creating a local aliasthat is controlled from within the application rather than through theBDE configuration files.
I. Start a new application and save it. Name the unit file dbaseu.pasand the project file dbasep.dpr.
2 . Place a Database component on the form. You may enter all of theproperty values through the Object Inspector but Delphi, as it oftendoes, offers a better solution. Double-click on the Database component[or right-click and select Database Editor) to invoke the Database Edi-tor. This tool, shown in Figure 5.14, conveniently gathers all of thenecessary property editors for building the connection.
Figure 5.I
The Datobose
Editor
3 . In this dialog, everything necessary for a BDE alias is going to be set.Enter ProjectData in the Name field. This is the alias by which thisconnection will be known. Because the settings for the database
142 n P a I-The Delphi Database Tools
5.
connection are going to be established through the component, skipover the Alias Name field to Driver Name. Select STANDARD fromthe list
The login parameters for each type of database can be set through theParameter Overrides field. To see the available parameters and their $default values, click on the Defaults button. For simplicity purposes, i:
we are going to point this connection to the Demos directory by plac- /_f?fing the full path in the Path parameter. Set this value (for Delphi 4) to: :-*2
I1C:\Program Files\Common Files\Borland Shared\Data
and click OK to establish the properties.
This local alias is now self contained within the application which nowh l t t l th tti T t t th ti l
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
133/347
6.
has complete control over the settings. To test the connection, place aDBGrid, DataSource, and Table component on the form. Set the
_ 1
DataSource property of the grid to ata ource and the DataSetproperty of the DataSource to Tablel. In the Table1 DatabaseName :
.property, drop-down the list of aliases. You will find the ProjectDataalias is now a recognized alias through the BDE. Select this item.Select the CLIENTS.DBF table for the TableName property.
Activate the Table component and the contents of the CLIENTS table .:will be displayed in the grid.
,:
As mentioned earlier, all of the alias control function is encapsulated ~~~~~~3within the Database component and controlled by the application.
,
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
134/347
Key \Voperties
ries, etc., that are activated as part of an application. All database and
dataset components are associated with the automatically generated
I:i
i
default session component, originally named Session. All sessions .,tq
within an application are in turn automatically managed within a listcalled Sessions. ~-s.t
The default Session component effectively manages all of the tempo- .{rary and persistent database components and it is only in the most , :demanding circumstances that you will need to create supplementarysession components. Applications that would require supplemental ses-
.;
:
sion components include those that create concurrent queries againstthe same dataset and multithreaded database applications.
The default properties of the automatically generated Session compo- ..&nent are rarely, if ever, changed. The properties detailed below and
listed in Figure 5.15 are required when you create a new session atdesign time or dynamically at run time.
Active
AutoSessionName
KeepConnection
Name
NetFileDir
False
False
True
Session I
This property specifies whether or not the
session is active.
Controls whether or not a unique session
name is generated when additional -
sessions are instantiated.
Creates a persistent connection even if the
dataset
is closed.
The internal name of this component.
The directory that contains the BDE file
PDOXUSRS.NET network control file.
144 n Part
Auto
PrivateDir The directory in which temporary files
associated with the session will be stored.
SessionName
SQLHourGlass True
A unique identifier for this session as it is
known to the application.
This determines whether or not the
mouse pointer changes to the SQL
hourglass during operations.
1 Tae This DroDertv is for the develoDers use.
Fieure 5. I5 T h e TSession combonent DroDerties
II-The Delphi Database Tools
8/10/2019 Tomes of Delphi - Win32 Database Developers' Guide
135/347
The Boolean property AutoSessionName determines whether or not a :
unique session name is automatically generated. This property is .. .$..*.ii
designed to ensure that multithreaded applications always have unique 3;session names regardless of r-he number of sessions created. When this .:
property is True, SessionName cannot be set. Also, a Session compo-$
..j .
nent cannot be added to a form or data module that already contains aSession component that has the AutoSessionName property set to True::.+
NetFileDir
The NetFileDir property specifies the location of the Paradox networkcontrol file PDOXUSRS.NET. Applications that work with Paradox filesuse this file to manage file sharing. All of the clients that share thesame database must use the same network control file.
PrivateDir
Similar to the previous property PrivateDir specifies the directory inwhich the BDE will create its temporary files.
i
Tip The performance of an application can often be measurably
improved if installed on a network by specifying a local subdirec-
tory as the location for the PrivateDir value. This allows the
temporary files to be created on the fast local driver rather than
having to travel the network to the server.
TSessionEvents
The Session component exposes two events, OnPassword and