Back


Database
by James M Sandbrook
Tokoroa, New Zealand.

‎Thursday, ‎19 ‎September ‎2002, ‏‎10:11:04 PM


Creating database applications is one of the main reasons many developers purchase Borlands Delphi.
After you install Delphi for the first time you will find that its not that hard to run a database project and one of the first things you should do if you are interested in database programming is have a look at the database demonstration examples that Borland has supplied with Delphi, you should find them in the \Delphi\Demos\Db directory on your hard drive.

If you have a look at the Data Access page on the Delphi component palette you will see the components that are used to communicate with databases in Borland Database Engine applications, like TTable, TQuery and TDataSource.
And on the Data Controls page you will also find the visual components that are used to show the contents of a database and also allow editing of these contents, like TDBNavigator and the very useful TDBGrid.

With Delphi you can create simple to very complex database applications and Borland has gone to a lot of trouble to help make this as simple as they can.

With Delphi 1 and 2 you could use the BDE (Borland Database Engine) for database programming, but when Delphi 3 came along your options increased and with the newer versions of Delphi you have a lot more options for accessing a database. Some examples are:
 

  • BDE - Borland Database Engine
  • IBX - InterBase Express 
  • ADO - Microsoft ’s ActiveX Data Objects
  • dbExpress


Not all versions of Delphi are capable of creating database applications and you may have to upgrade to the Professional or Enterprise versions to do this.

The latest news is that Borland will no longer be updating the BDE but this is no reason for you to stop using it, we will still have many examples that use the BDE mainly because most Delphi developers are still using older (than version 6) versions of Delphi and the BDE is still in use world wide.
 


First Database Application Creating a New Paradox Table
Creating an Alias Borrow A Table Structure Example
Setting up a Master/Detail relationship example Viewing and saving a database to a text file
Changing the DBNavigator Button Images About DataSet States
DBNavigator Buttons  
Opening a Dataset:

In order for you to do anything with a dataset you first have to open it.

Table.Active := True;  //Does what we want or you can use

Table1.Open;

If you use Table1.Open this will also set the Active property to True as well.

Closing A Dataset:

Table1.Active := False;

Table1.Close;
 

Counting The Records In A Table:

procedure TForm1.Button1Click(Sender: TObject);
begin
  with Table1 do
   ShowMessage(Format('Count = %d', [RecordCount]));
end;
.

Filtering is a very useful way for your program users to find specific data in a database based on special criteria. 

The software user sets specific conditions for the filter and the result is displayed. 

In order to enable filtering you must set the Table filtered property to true. 

Example: 

Table1.Filtered := True; 

But first you specify the filter conditions in the Filter property. 

Here is an example: 

procedure TForm1.Button1Click(Sender: TObject); 
begin 
    Table1.Filter := 'Continent =' + QuotedStr(Edit1.Text); 
    Table1.Filtered := True; 
end; 

The above example creates a filter that uses the datasets 'Continent' field and a TEdit component for the user to enter
text as well. Note that after we have set the details for the filter then we set the Filtered property to True. 

If I were using the country.db and typed in Edit1 'North America' then all the records with North America in the Continent field, would only be displayed. 

To view all the records again you can set the Filtered property to False like this: 

procedure TForm1.Button5Click(Sender: TObject); 
begin 
    Table1.Filtered := False; 
end; 
 

Not Showing The Password Dialog Box:

If you have a Paradox database and you have added a password but you do not want your program users to have to type in the password, in other words you do not want the user to see the password dialog box, then you can use this code:

procedure TForm1.FormActivate(Sender: TObject);
const CRLF = #13 + #10;
begin
    Session.AddPassword('PassWord');
    try
     Table1.Open; 
    except
       on E:Exception do
     begin       // exception if we  cannot open the table
         ShowMessage('Error!' + CRLF + // this is to display an error explaining what happened
                   E.Message + CRLF + 'Terminating application...');
         Application.Terminate; //Shut down the application
     end;
end;

Showing The Selected DBGrid Field Name In A Label:

Label1.Caption := DBGrid1.Columns.Grid.SelectedField.AsString;

Bookmarks:

The 32 bit versions of Delphi still support GetBookmark, GotoBookmark and Freebookmark this is to maintain backward compatibility with the older 16 bit (Delphi 1) database projects.

Here is an example using GotoBookmark, GetBookmark and Freebookmark.

var Bookmark : TBookmark;

procedure TForm1.FormCreate(Sender: TObject);
begin
    Bookmark := nil;
end;

procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
    if BookMark <> nil then Table1.GotoBookMark(BookMark);
   Table1.FreeBookMark(BookMark);
    Bookmark := nil;
end;

procedure TForm1.SpeedButton2Click(Sender: TObject);
begin
    if Bookmark = nil then
    BookMark := Table1.GetBookmark;
end;

---

TDataSet.Bookmark

Used to specify the current bookmark in a dataset.

type TBookmarkStr: string;
property Bookmark: TBookmarkStr;

Example:

private
    { Private declarations }
    MyBookmark : TBookmarkStr;

Button1.Caption := 'Bookmark';
Button2.Caption := 'Clear Bookmark';
Button3.Caption := 'Go to MyBookmark';

Add 3 TButton components to your form, double-click on each button and add this code:

procedure TForm1.Button1Click(Sender: TObject);
begin
    MyBookmark := Table1.Bookmark; 
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
    MyBookmark := ''; 
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
  Table1.Bookmark := MyBookmark; 
end;


Find Nearest: (Database)

Table1.FindNearest ([Edit1.Text]);

Navigate a Table:

Table1.Last = takes you to the last record.
Table1.First = takes you to the first record.
Table1.Prior = takes you to the previous record.
Table1.Next = takes you to the next record.

Table1.MoveBy(n) = takes you forward n records.
Table1.MoveBy(-n) = takes you back n records.

Where n is a number.

Drop a Table on a form:

If you have Database Explorer (SQL Explorer) you can drag and drop a Table onto the Delphi form, from Database Explorer.
This is a fast way of setting up a database.
When you do this the Table and DataSource are put on the form as well.

You can also drop a single field onto a form.

An example is for you to go to employees.db in Database Explorer, expand the Fields tree node (Click on the +) next
click on the EmpNo field and drag it onto a form.
You should see:
 

  • Lable1 = Caption = EmpNo
  • Table1
  • DataSource1
  • DBEdit1
By doing this you can drag individual fields onto a form.
Fields Editor:

To see the Fields Editor, double click on Table1 or right-click on Table1 and then select 'Fields Editor', you can also do the same with Query1 (TQuery).

Right-click on the Fields Editor and you can select 'Add Fields', select the fields you want and then click on 'OK'.
When you can see all the fields in the Fields Editor, you can then select one of the fields, say in this case we want 'Name' from DBDEMOS - ANIMALS.DBF.
You can then drag the field onto the form.

You can use the Fields Editor to add new fields to a table.
 

IndexName:
[property IndexName: String;]

Unit DBTables

This property is used to specify the sort order of the table. By changing the IndexName, the order will change. 
By default the IndexName is set to null, so the BDE uses the primary index for sorting the table.
Using the secondary index you can change the sort order.

Examples:

procedure TForm1.IndexSubject1Click(Sender: TObject);
begin
  Table1.IndexName := 'SubjectIDX';
  Table1.FindNearest(['AAAA']);
end;

procedure TForm1.IndexTipsTitles1Click(Sender: TObject);
begin
  Table1.IndexName := 'TipNameIDX';
  Table1.FindNearest(['AAAA']);
end;

You can use Table1.IndexName := ''; to go back to the primary index.
.

DBNavigator.BtnClick:
[procedure BtnClick(Index: TNavigateBtn);]

Is the same as clicking on a DBnavigator button.
The example is the same as clicking on the post button, and is interesting because it will save the text (data) in the DBMemo to a file before the user clicks on SpeedBtn1.
 

procedure TForm1.SpeedBtn1Click(Sender: TObject);
begin
  DBMemo1.SaveToFile(DBEdit1.Text + '.txt');
  DBNavigator1.BtnClick(nbPost);
end;

Here are you options for the buttons:

First       nbFirst         Goes to the first record
Prior      nbPrior        Goes to the previous record
Next       nbNext        Goes to the next record
Last       nbLast        Goes to the last record
Insert     nbInsert       Inserts a blank record
Delete  nbDelete     Deletes the current record
Edit      nbEdit          Permits the user to edit the current record
Post     nbPost         Posts the current record
Cancel nbCancel    Cancels the current edit
Refresh nbRefresh Refreshes the data in the dataset
.

Listing Field & Object Names:

I opened the Borland CtrlGrid Db demo and added a button to the FmCtrlGrid form and a TListBox (ListBox1) and aligned ListBox1 to alBottom after dragging down the form so it was larger. And then I double-clicked on the button (Button2) and added this code:

procedure TFmCtrlGrid.Button2Click(Sender: TObject);
var I : Integer;
begin
    ListBox1.Clear;
    for I := 0 to DM1.tblIndustry.FieldCount - 1 do
       ListBox1.Items.Add(DM1.tblIndustry.Fields[I].FieldName);
end;

This gave me a list of the fields in the table tblIndustry.
--
Then I added another TButton (Button3) to the same demo and then double-clicked on Button3 and added this code:

procedure TFmCtrlGrid.Button3Click(Sender: TObject);
var I : Integer;
begin
    ListBox1.Clear;
    for I := 0 to DM1.tblIndustry.FieldCount - 1 do
      ListBox1.Items.Add(DM1.tblIndustry.Fields[I].Name);
end;

DatabaseName:

You can select an alias by clicking on the little black arrow to the right of 'DatabaseName' in the Object Inspector, or you can type in a path.
You can also use code like this:

Table1.DatabaseName := 'd:\delphi 3\demos\db';

A Table should not be open when you change the DatabaseName.

TReport Component: (Delphi 3, other versions?)
To find this component, go to Component, Configure Palette, under Pages scroll down until you see the word [All].
Click on [All].
Then on the right side under Components, scroll down until you see the component TReport.
Click on TReport.
Then click on the Show button.
TReport is a wrapper for the Borland ReportSmith application.
TTextDataSet Component: (Delphi 3, other versions?)
This little gem is hidden in the Delphi 3\demos\db\textdata directory (Folder).
IDAPI = Integrated Database Application Programming Interface.
BDE = Borland Database Engine.
Borland Database Engine:

When installing the BDE, it is recommended by many programmers to do a full install of the BDE. Although it is possible to do a partial install, it is better to do a full install.

You are allowed to distribute the BDE with your database applications, this is not the BDE installation from your Delphi CD, you must use a program like the free lite version of InstallShield that comes with Delphi.
 

...
Paradox Tables Extensions:
.DB This is your Table Data. You should restore this if your PC crashes.
.MB (BLOB) Binary Large Object data. This is used for Formated Memo, Memo, Graphic, Binary, and OLE field types.
.VAL Stores the settings for validity checks and referential integrity.
.PX  "Primary Index", this file controls the Primary sort and search order for your Table.
.XG?,
.YG?
"Secondary Indexes", These secondary index files manage alternative sort and search orders for your Table.
.TV This stores the manner in which the Tables is displayed in the Database Desktop, such as the column order and width.
.FAM Used in conjunction with the .TV file.
...

Back