General Information Home Who Are We? Contact Us What is Firebird? IPL License Events Blogs Paul Beach Philippe Makowski Dimitri Kuzmenko Other Languages www.ibphoenix.cz www.ibphoenix.fr Services Service & Support Training & Consulting Products Developer CD Deployment CD IBReplicator dbFile IBAnalyst IBFirstAid IBBackupSurgeon IBUndelete FBScanner Firebird Book Firebird Goodies Firebird Appliances Shop Online IBPhoenix Shop Development Firebird Development Vulcan Development General Documentation Function and Design Other Links Community Firebird Conference 2006 Firebird Conference 2005 Get Involved Member Websites Projects News News Archive Groups, Lists, and Forums IBPhoenix Development Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro... 1 de 42 06/04/2010 18:22
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
General Information
Home
Who Are We?
Contact Us
What is Firebird?
IPL License
Events
Blogs
Paul Beach
Philippe Makowski
Dimitri Kuzmenko
Other Languages
www.ibphoenix.cz
www.ibphoenix.fr
Services
Service & Support
Training & Consulting
Products
Developer CD
Deployment CD
IBReplicator
dbFile
IBAnalyst
IBFirstAid
IBBackupSurgeon
IBUndelete
FBScanner
Firebird Book
Firebird Goodies
Firebird Appliances
Shop Online
IBPhoenix Shop
Development
Firebird Development
Vulcan Development
General Documentation
Function and Design
Other Links
Community
Firebird Conference 2006
Firebird Conference 2005
Get Involved
Member Websites
Projects
News
News Archive
Groups, Lists, and Forums
IBPhoenix Development
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
1 de 42 06/04/2010 18:22
Powered by Firebird
Users of Firebird
Publications
History
Web Hosting
Downloads
Main Downloads
InterBase®
Contributed
Research
Research Center
Articles
Examples
FAQs
Search
Search KnowledgeBase
Search Web Site
Search Mers List
Partners
Partners
This Site Uses:
Delphi to InterBase in 15 Minutes
Contents
Delphi to InterBase in 15 minutes
Chapter 1 - The 15 minute steps
Chapter 2 - 10 minutes to setting up InterBase
Chapter 3 - 5 minutes to setting up Delphi
Reducing the learning curve
Chapter 4 - Some practical issues
Chapter 5 - Delphi InterBase components
Chapter 6 - SQL
Chapter 7 - Stored procedures
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
2 de 42 06/04/2010 18:22
Status of the guide
Chapter 8 - Guide updates and limitation of liability
The text below references several demo files. These can be
downloaded by clicking on these three links:
DelphiToInterbasePAS.zip
DelphiToInterbaseSQL.zip
IBDemos.zip
Chapter 1 : The 15 minute steps
1.1 Setting up InterBase - 10 minutes
Step 1.1 - Create the database
Step 1.2 - Create the tables
Step 1.3 - Create the indexes
Step 1.4 - Populate the tables
Step 1.5 - Create stored procedures
1.2 Setting up Delphi - 5 minutes
Step 2.1 - Pop up a TIBDatabase component and fill in details
Step 2.2 - Pop up a TIBTransaction component and fill in details
Step 2.3 - Pop up a TIBTable component, a Datasource and a
DBGrid and DBNavigator
Chapter 2 : 10 Minutes to setting upInterBase
This Chapter is written on the basis that the InterBase SQL files
linked to this guide (Tables.SQL and Indexes.SQL) are open within
a simple text editor (such as Notepad or Delphi). If you read the
guide in conjunction with the SQL files, the points below should be
simple to follow.
2.1. Create the database
Background
First, you need to create the database. This is the file structure
within which InterBase will subsequently store both the table
structure, indexes etc. (called the Metadata), and the data itself
(called the Data).
Do it!
To create the database:
Open IBConsole (Problems? Go to Using IBConsole)1.
Click "Database, Create Database"2.
Enter the Database path name and database name3.
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
3 de 42 06/04/2010 18:22
(Networks? See Database locations)
Enter user name and password (Special considerations? Go to
creating a database in IBConsole)
4.
Click the "Create" button5.
2.2 Create the tables
Background
Next, create the table structures. This can be achieved in several
ways. The easiest way is to take a simple text file, fill in the table
structure, and "import" the structure to InterBase using IBConsole,
as explained below. There is a separate section covering "Importing
database changes using a SQL file" which will be of interest when
you need to carry out the Importing process for the second time.
A simple text file has been provided with this guide (Tables.SQL)
with illustrative file layouts. Change the layout(s) to the layout(s)
you require, and import the structure into InterBase. You can
change it easily later. Those who don't feel comfortable with what
they are doing might want to see Creating tables - Tips, prior to
"doing it".
Do it!
To create the tables:
Open "Tables.SQL" in any text editor (eg. Notepad, Delphi)1.
Change the file location within the "Connect" statement to
the location to which you saved the Database
2.
Change the "user" and "password" to the username and
password used to create the database
3.
Change the Table layout to the layout you want. (Want help
with Datatypes? See InterBase Datatypes)
4.
Save the file (Latest changes not used by InterBase? See
Creating tables - Tips )
5.
In the program IBConsole, click "Query, Load script"6.
Find the SQL file you saved, and click "Open".7.
Comment out the "Connect ... " statement (How? See
Comments paragraph in Chapter on SQL)
8.
Click "Query, Execute"9.
If you want the confirmation and/or the error messages to
appear in the IBConsole window, click the "No" button. If you
prefer them to be saved to disc in a simple text file, click the
"Yes" button and give the program a file name and location to
which the results will be written.
10.
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
4 de 42 06/04/2010 18:22
If successful - you will be told (well done!). (Failure? See
Handling SQL script errors)
11.
2.3 Create the indexes
Background
Indexes allow InterBase to locate data (dramatically) more quickly.
An index has two key components to it - the field(s) that you will
want to search on and whether the field(s) are unique (e.g. a
Reference number will probably need to be unique, but you may
well need to accommodate several people sharing a birth date or a
last name).
One particular type of index that is usually needed is an index on
the Field(s) which uniquely identify a record within a table (e.g. the
unique reference number given to each record, or a Social Security
ID, or a post code and House number/name combination within an
Address table). This is called the Primary key. Those who don't feel
comfortable with what they are doing might want to see Creating
indexes - Tips, prior to "doing it".
Do it!
Creating the Primary Key
Open your "table.SQL" file.1.
Add a line at the bottom of the definition, immediately before
the final ")", and add the phrase (with the comma in front)
, PRIMARY KEY (field)
where field is the name of the field(s) you want as the
primary key, eg:
, PRIMARY KEY (REF) or another example: , PRIMARY KEY
(LASTNAME, FIRSTNAME, POSTCODE)
2.
If you have already created your table, see Creating indexes
- Tips
3.
Creating other Indexes
Open the "Indexes.SQL" file1.
Add a new index with the syntax (don't forget the semi-colon
at the end): CREATE INDEX NAME ON ANIMALS(NAME);
where "Animals" is the name of the table, and "Name" is the
field on which to index (sort)
2.
2.4 Populate the tables
Background
When the database has been created, and the structure set up, you
may want to fill up the database with test data. This can be
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
5 de 42 06/04/2010 18:22
achieved through the "old-fashioned" technique of manually
entering data into the database (especially if you have already set
up the Delphi side which allows data entry).
A more robust technique is to create a series of SQL commands
that insert data to the table within a simple text file, and import
the SQL file to InterBase.
The advantages of this approach include the ability (a) to copy,
paste and update lines to achieve a methodical selection of all types
of data more easily, (b) to re-enter the data whenever you choose
to clear all the data from the database and start again and (c) to
reuse relevant test data within new database applications in future.
Do it!
To populate the database using this method:
Open "TestData.SQL" in any text editor (eg. Notepad, Delphi)1.
Change the file location within the "Connect" statement to
the location to which you saved the Database
2.
Change the "user" and "password" to the username and
password used to create the database
3.
Amend the test data. (Why this format? See InterBase SQL
reference guide - "Insert" commands)
4.
Save the file (Latest changes not used by InterBase? See
Handling SQL script errors )
5.
In the IBConsole program, click "Query, Load script".6.
Find the SQL file you saved, and click "Open".7.
Comment out the "Connect.." statement (How? See
Comments paragraph in Chapter on SQL ). Click "Query,
Execute"
8.
If you want the confirmation and/or the error messages to
appear in IBConsole, click the "No" button. If you prefer them
to be saved to disc in a simple text file, click the "Yes" button
and give the program a file name and location to which the
results will be written.
9.
If successful - you will be told (well done!). (Failure? See
Handling SQL script errors)
10.
2.5 Create stored procedures
Why and when?
Stored procedures are arguably some of the most powerful features
of InterBase.
Almost (but not quite) everything that can be achieved through
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
6 de 42 06/04/2010 18:22
Stored Procedures can also be achieved by sending SQL commands
from Delphi to InterBase. But the programming time can increase
well more than tenfold, and the running time can increase by vast
factors in certain circumstances. To start using InterBase, stored
procedures are not necessary. To program Database applications
more quickly and to run faster, it is well worth learning how to use
Stored Procedures - a learning curve that should be shallow for
most programmers with the help of the Stored Procedures section
in this guide. Some background to Stored Procedures is set out
below:
Background
Stored procedures fall into two main categories:
procedures that update the Database's Metadata (What's
that? See Create the database).
1.
procedures that handle the Database's data, such selecting
specified items (eg. people older than 12) or modifying data
(such as inserting a new address, editing an existing address,
updating a wage rate by a calculated percentage or deleting a
group of employees from a table where the record matches a
record in another archive table)
2.
The stored procedure is similar in concept to a Delphi procedure or
function. It is programmed directly into InterBase to:
accept input parameters (if there are any), provide formatted
output parameters giving single item output (such as the
total of relevant sales invoices),
1.
provide formatted output parameters (if there are any) giving
a result set (such as every invoice detail that corresponds
with an invoice reference), or
2.
simply modify the database information using conventional
programming techniques (such as updating records if the
department value is greater than one value but less than
another)
3.
The stored procedure can be "called" either from within a Delphi
program (How? See the Delphi components section), from within
another InterBase Stored Procedure (using the InterBase SQL
command Execute Procedure ) or from any other program capable
of "calling" the stored procedure (such as the IBConsole program
that comes with InterBase).
The syntax used to "call" the stored procedures depends on what
the stored procedure does. An example of the syntax would be
SELECT * FROM SP_NEW_RECRUITS('4/1/1999','12/1/1999') to
select all new recruits who joined a company within two dates, and
EXECUTE PROCEDURE SP_ARCHIVE_RECORDS('Sales and
Marketing') to archive records from the Sales and Marketing table.
The use of Stored Procedures is so powerful, there is a section even
in this "Introductory" guide to InterBase, with some examples of
Stored Procedures we have used within our own programs to
illustrate the power and syntax of the facility - see the Chapter on
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
7 de 42 06/04/2010 18:22
Stored Procedures. The full technical specification of using Stored
Procedures can be found in the InterBase manuals, in several
places depending on what you are looking to achieve).
Chapter 3 : 5 minutes to setting up Delphi
This Chapter is written on the basis that the Demo Delphi project
"DelphiDemo.dpr" linked to this guide is running within Delphi. If
you read the guide in conjunction with the program, the points
below should be simple to follow.
3.1 Database component (TIBDatabase on
InterBase tab)
Drop a TIBDatabase component onto a Form (or DataModule if you
use them). The configuration is in two places:
Object inspector
Connected - leave as false. Set to true when ready to see if
the component is set properly.
1.
Database name - Fill in the file location and name (File can't
be found? See Database locations)
2.
Default transaction - See TIBTransaction component below3.
Login prompt - If you want users to login, leave as false. If
not, set to true AND see step c.
4.
Params - set if step c. is not enough5.
Double click on the component for the Property editor
Connection - leave as "local" if InterBase is running on your
machine. Otherwise, set to "remote" and see InterBase
Network issues
1.
User Name - Enter the UserName used to create the
Database (but note points relating to Login prompt). Leave
blank if you do want the User to type in their own User name.
2.
Password - Enter the Password used to create the Database
(but note points relating to Login prompt)
3.
Login Prompt - Set to Ticked if you want users to enter their
username and password. Set to Blank if you want InterBase
to use the UserName and Password you have entered in the
TIBDatabase Component (see above). Note - InterBase gives
you the capability to allocate different users with different
rights. If you want to make use of this facility, you will need
to leave the Login prompt ticked.
4.
There is a trap for the unwary when opening and closing a
database using the component. To avoid the trap, see
Opening and Closing a database using Delphi - Tips
5.
3.2 Transaction component (TIBTransaction
on InterBase tab)
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
8 de 42 06/04/2010 18:22
Background
InterBase allows you to collect a group of modifications and
commands together and process either all of them or none of them.
The commands are, of course, processed sequentially (such as
Check stock line exists, then if it does, update the stock table, then
issue a sales invoice, then update the sales table).
The problem that InterBase solves is where there is a break after
some transactions have been processed, but before others within
the collection have not. An example is where stock is updated but,
for some reason, the sales invoice should not be raised. Without
solution, the stock level would no longer "match" the sales levels.
With the solution, InterBase collects all commands (also called
transactions) together, processed the batch and if anywhere along
the line there is a failure before all the transactions are completed,
all transactions that have already been processed are rolled back).
InterBase solves the problem by allowing the Delphi programmer to
"mark" within the Delphi program where a collection of commands
starts (with the Delphi command TIBTransaction.StartTransaction)
and where it ends (with the Delphi command
TIBTransaction.Commit or TIBTransaction.Rollback. When each
transaction is "processed", it is simply held in a temporary location
with the command being carried out only on a temporary basis,
pending the Commit command. When the programmer issues the
command TIBTransaction.Commit in the Delphi program, all
transactions within the group are finally processed. When the
programmer issues the command TIBTransaction.Rollback in the
Delphi program, the commands are removed from the temporary
location and the data restored to the state prior to the first
command where the StartTransaction command was issued.
There is one conceptually strange aspect to the Transaction
component. InterBase will not operate other than in the context of
a Transaction. However, once the Transaction component has been
hooked up (see below), there is no requirement that you activate
the Start and End of the Transaction in your program. If the
Transaction is in place, you are able simply to issue a database
command (say, to update a record in a table), and the Transaction
assumes you mean for it to start just before the command is
processed, and for it to end just after the command has been
processed, unless you override the default behavior with the
StartTransaction and Commit/Rollback instructions. The
Transaction will be committed for you when the Database is closed
(or when the program is closed if that comes first).
Do it!
Drop a TIBTransaction component onto the Form (or DataModule if
you use them). To configure the component:
All defaults can be accepted1.
In the TIBDatabase component, set the Default Transaction to
the name of the TIBTransaction just created.
2.
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
9 de 42 06/04/2010 18:22
3.3 Displaying the InterBase data in the Delphi
program
Background
Once the TIBDatabase and TIBTransaction have been set up,
everything is programmed as any other database application.
Do it!
To display the InterBase Database:
Pop a TIBTable component onto the form (from the InterBase
tab)
1.
Set the Database property to the TIBDatabase component's
name
2.
Set the Table property to the Table you want to display3.
Pop a TDataSource component onto the form (from the Data
Access tab)
4.
Set the Dataset property to the TIBTable component's name5.
Pop a data aware control, such as a TDBGrid (from the Data
Access tab)
6.
Set the Datasource property to the TDatasource component's
name
7.
Pop a TDBNavigator on the form (from the Data Access tab)8.
Set the Datasource property to the TDatasource component's
name
9.
Set the TIBTable's "Active" property to True10.
Save and run the program11.
Chapter 4 - Practical issues
4.1 Creating tables - Tips
4.2 Creating indexes - Tips
4.3 Opening and closing a Database from Delphi - Tips
4.4 Database locations
4.5 Network issues
4.6 IB Console - Running SQL files
4.7 Creating a SQL script file
4.8 Handling SQL script errors
4.9 InterBase Datatypes
4.1 Creating tables - Tips
This section expands on Creating tables from section 2.2. It is
designed for those who don't feel comfortable creating tables
without some further guidance. For a detailed specification on
creating tables, see the InterBase guide "Data Definition Guide".
Every comma and semi-colon is significant. Watch for
inadvertent deletions. (More detail? See Creating a SQL
script)
1.
If you are unsure whether you want a Primary Key, see (2.3)
Create the indexes.
2.
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
10 de 42 06/04/2010 18:22
Don't use referential integrity facilities at this stage3.
Keep the file structure simple. It is easy to make it more
complex later.
4.
Don't fill in large amounts of test or real data to a
column/field that may subsequently change, since it is a
fiddly process to change the definition of a column/field (eg. a
REF field from an INTEGER to a VARCHAR(10), or an
AMOUNT field without a default value to an AMOUNT field
with a default value ) which already has data in it.
5.
When you have amended an "SQL" file, save it before
importing it. Otherwise, InterBase will import the version
before you made any amendments - or, more accurately, the
version that was last saved.
6.
4.2 Creating indexes - Tips
This section expands on Creating indexes from section 2.3. It is
designed for those who don't feel comfortable creating indexes
without some further guidance. For a detailed specification on
creating indexes, see the InterBase guide "Data Definition Guide".
If you want to create a Primary key, and you have already
created the table, the format of the SQL command to achieve
the Primary key is:
ALTER TABLE ITEMS ADD PRIMARY KEY (REF);
although you can not create a second primary key if one
already exists
1.
For details of the Create Index rules, see "Create Index" in
the InterBase SQL reference manual.
2.
4.3 Opening and closing a Database from
Delphi - Tips
One tip - in the BDE, the Database is closed for you when you exit
the program. This is not so with the InterBase Express components.
The solution is to have a IBDatabase1.close statement in the
Form.OnClose event (or similar). If you forget to close the
Database explicitly, it stays "open". If you try to open a database
that is already open, using the TIBDatabase component, you get an
error message. The solution is always to check with the database is
open before opening it (eg. of Delphi : if not
(IBTransaction1.connected) then IBTransaction1.open; ) and closed
before closing it (eg. of Delphi : if (IBTransaction1.connected) then
IBTransaction1.close; - Note that when you close a database, the
Transaction and any other component "connected" to that Database
is also disconnected for you, whether you intended it or not.)
4.4 Database locations
The InterBase components do not work with the BDE, so no Aliases.
Instead, you need to use the absolute location when filling in the
location of the database (and its file name).
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
11 de 42 06/04/2010 18:22
In Windows, file locations follow the familiar pattern
"c:generalInterBasefilename.txt". For a networked drive, (mapped,
say to f: which is on the machine name "Machine2"), the pattern
for the location is "f:generalintertbasefilename.txt"
InterBase is well geared up for dealing with both internal and
external networks. It has to be a little more sophisticated. In some
circumstances, this notation works fine. In others (particularly
where you are involved with internet Web applications and/or the
TCP/IP protocol within your internal network), you have to precede
the file location name with the machine name, eg.
"Machine2:c:generalInterBasefilename.txt". Note the absence of
the "" character between the machine name and the machine's
local file location.
When using TCP/IP, you will need to "tell" InterBase where the
machine (eg. Machine2) can be found. This is done very easily by
editing the file called "hosts" (note not hosts.sam, which is
something quite different). This file can be in more than one place,
and is easily found by a Windows search of the Windows or WinNT
directories (including sub-directories) for the file "hosts" (in our
configuration, Hosts is found in the WinNTSystem32driversetc
directory). When found, open the file with a simple text editor
(such as Notepad or Delphi) and add at the end of the file the line
which "identifies" the IP address with its machine name.
An example of the entries might be (note that the # sign means a
comment follows):
#IP
address
#Machine
name#Comments
127.0.0.1 localhost
192.1.1.1 Machine1#This is a local machine with
address 192.1.1.1
192.1.1.2 Machine2#Local machine, referred to
as Machine2 by programs
99.876.78.9 MyISPMachine#External machine with
address 99.888.77.66
Another possible file you may need to edit is the Services file. You
can find it the same way as you found the hosts file. InterBase
needs to have the line below added in. It should have been added
in automatically during installation. But on occasions, you may
have to add it "manually. If so:
Open the Services file1.
Add the line below
gds_db 3050/tcp
2.
4.5 InterBase - Network issues
InterBase can work with three network protocols, TCP/IP,
NamedPipe and SPX. InterBase must be configured to use the
protocols used by your network.
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
12 de 42 06/04/2010 18:22
If you have the choice, use TCP/IP, since there are situations where
the others will not run. For a detailed explanation of the
performance issues where you have the choice of protocols to use,
check out the InterBase manuals.
If you are using TCP/IP, be sure to check out the section on
Database locations.
4.6 Using the IBConsole
IBConsole is a program written to allow easy access to InterBase. It
enables you to create a Database, to set up and amend the
Metadata (what's that? See Create the Database), and to insert,
update, delete and query data in the database.
This guide explains just a few of the issues relating to using
IBConsole, to encourage its use for "no fuss" access to the
database.
Open the program (for Windows users .. "Start, Programs,
InterBase 6, IBConsole"), then
To create a new database, click "Database, Create Database",
and fill in the blanks. For assistance, the database name must
include the path to the directory in which you want to store
the database. The Username and Password are important in
the respect that it is the default name and password
combination that give you full access to the database in
future. Do not use generic names/passwords (such as
"SYSDBA" and "masterkey") if you want to control people
accessing the data who you may have concern about access.
Conversely, try to avoid setting up a database whose name
and password you can not remember - you will not be able to
connect to it from the time you have forgotten. If you have to
use a "Remote server", and you have to make a selection
about which network protocol to use, try the TCP/IP protocol
if your network has access to TCP/IP and if don't have a clue
about the others.
1.
If you have already created a database, click "Database,
Connect", and fill in the blanks. Once you have connected to
a Database, you then have full access (subject to the rights to
which you may have been constrained by someone else with
control over the Database you are reviewing).
2.
Much of the time, you will want to run SQL commands. For
this you use the ISQL window, which you get access to by
clicking "Tools, Interactive SQL"
3.
The top window allows you to enter SQL commands
(Examples? See the Chapter on SQL). This is particularly
useful for checking whether a SQL statement does what you
expect, before entering it into a Stored Procedure. To
"execute" the command, type it is and click the Lightening
hot key (or click "Query, Execute). To rerun (or pull up to
amend) a previous query, click the back arrow with the
symbols "<--?", make any changes you want, and execute
the command again.
4.
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
13 de 42 06/04/2010 18:22
The bottom window contains the results of the query. If you
want to print the output, you can click "Query, Save output",
give a file name and open the text file in any simple text
editor (such as Notepad or Delphi).
5.
To disconnect from a database, click "Database, Disconnect".6.
When you have "executed" an action in the top window, you
generally have the option to Commit or Rollback (via
"Transaction, Commit" or "Transaction, Rollback"). Rolling
back reverses any change to the database since the start of,
if later, the previous commit or rollback. Committing does two
things. Firstly, it makes permanent any changes you have
made to the database (metadata and/or data). Secondly, it
"refreshes" your dataset. If you are working on a database
file, and the data is changed outside of the IBConsole (
EITHER by someone else OR you where you change the data
through, say, a test Delphi program or through another
instance of IBConsole connected to the same database), the
changes are not reflected in your session of IBConsole which
is working on a cached version of the data. When you Commit
or Rollback, the cached version is "thrown away" and you will
access the current version of the data from the main
database itself. The Commit command will clear the output
window at the bottom, so you will have to re-run your SQL
query, for which you can use the "<--?" hot key.
7.
The final - and crucial - guide in this section explains how to
"import" SQL to the database. You always have the option to
type the SQL commands directly in the top window. But there
are several commands that are better to enter in groups
(such as the setting up of a table, whose structure is far
easier to formulate as a group, than entering each field one
by one). In order to import the SQL, set up a simple text file
in any text editor (such as Notepad or Delphi), and save it
with the extension "SQL" (not mandatory, but it saves one
step further along the line). See the section on Creating a
SQL script file for what to include in the file.
When you are ready, save the SQL file. Within the ISQL
window, click "Query, Load script". Find the file, and click
"Open". You then need to comment out the "Connect.." or
"Create database.." statements. Comment out means enclose
the statements within the comment symbols (eg. of sql : /*
Connect database 'IBDemos.gdb' */ ). The statement has to
be in the script to allow you to run the SQL script from
outside IBConsole, but IBConsole will not allow you to run a
script without having first connected to an existing database.
The solution is simple - connect to the database first. (How?
See parapraph on connecting). Then, to execute the script,
click "Query, Execute".
The results of the Execution will either be "Your request was
successful" (in which case, well done), or it will give you an
error message. Every error we have ever encountered at this
stage has been Syntax errors. The error messages are close
to the most cryptic and unhelpful you may ever encounter.
For this reason, we would recommend you take very careful
note of the syntax rules in Creating a SQL script file, and try
8.
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
14 de 42 06/04/2010 18:22
to avoid making mistakes in the first place - which is
surprisingly possible.
4.7 Creating a SQL script
A SQL script is a simple text file that contains a series of SQL
commands that are run together as a series. There are many times
this is preferable to entering SQL directly to a database line by line
through IBConsole (What? see Using IBConsole). Using a SQL script
file is very easy, but as with all program code, the Syntax has to be
exact, and the rules appear inconsistent and run contrary to the
instinct of a Delphi programmer.
The easiest way to get the script (and the Syntax) right is to crib
from an existing file with the correct syntax. The zip file contains
several files with the extension ".SQL". You should open one of
them when looking through this part of the guide to make it easy
to understand what is going on.
To put a comment within the SQL script file, use the symbols
/* to start the comment, and */ to end it. Carriage returns
within a comment do not "cease" the commenting out. (This
is more useful that you would imagine - see the last
paragraph in this section for one circumstance where the
commenting symbols are invaluable)
1.
The "Connect" statement is essential. This both connects to
the Database you want to update, and enters the Username
and Password (eg. of sql : CONNECT
"machine1:c:generaldataIBDemos.gdb" USER "SYSDBA"
PASSWORD "masterkey"; - Note that the machine name is
required without "" if connecting to a database on another
machine, and note the position of the semi-colon at the very
end)
2.
There are two kinds of SQL you will enter. One kind is an
entirely self contained statement (such as SET GENERATOR
ORDER_GEN TO 138; - there is no break anywhere in the
statement which is relevant to InterBase ), and the other is a
series of statement that can not be interpreted without
identifying there is a break within the statement (such as
CREATE TABLE ORDERSDETAIL (REF INTEGER NOT NULL,
ORDERREF INTEGER NOT NULL, STOCKREF INTEGER NOT
NULL); - without the comma, InterBase would not have know
whether ORDERREF was the start of a new field or an error in
typing). The problem this paragraph deals with involves
identifying a break which represents the end of the
statement, distinguishing it from a break within the
statement. The problem arises only because the standard
Delphi symbol used for a break is the semi-colon (';'). This
break symbol is used within a stored procedure to identify
that the end of a SQL statement has arrived and the next
SQL statement is coming. And it is also used within a SQL
script to identify that the next SQL script statement is
coming.
The solution provided by InterBase is to allow you to define
your own "break" symbol for the SQL script file. When you
set this symbol (we use '^', others use '!!', and you can use
3.
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
15 de 42 06/04/2010 18:22
whatever you feel comfortable with), you continue to use the
';' symbol to identify the break of a sql statement within a
stored procedure, but to identify the break of the SQL script
statement (such as to denote the end of the Stored Procedure
itself), you then use your self-defined symbol.
To set InterBase to start to recognise the break symbol, use
the instruction : SET TERM ^ ; - Note the semi-colon is still
required to denote the end of this SQL script statement. To
switch this symbol off, use the instruction SET TERM ; ^ -
Note the self-defined break symbol is still required to
terminate this statement, but all subsequent statements will
break with the conventional ';' symbol. Within the SET TERM
pair of instructions, any SQL script statement termination
uses the defined symbol (eg. of sql : SET GENERATOR
ORDER_GEN TO 138^ ). BUT, where you are creating a
stored procedure with distinct SQL statements within the
Procedure, each statement must continue to use the
conventional ';' symbol, or the Stored Procedure will not
operate properly when it is at a later date.
This solution, which is not really so cumbersome once you
have the Syntax right, is confused by the way that a BEGIN ..
END pair is terminated in an InterBase stored procedure.
Where the BEGIN .. END is within the definition of a Stored
Procedure, you do not terminate the END statement, other
than at the very end of the Stored Procedure where you use
the self-defined SQL script termination symbol to denote the
end of the Stored Procedure. But within the Stored
Procedure's definition, you may use a begin .. end set within
an 'IF' type clause, in which case the End IS terminated with
the ';' symbol. For more details, see the Chapter on Stored
Procedures.
The SQL script file is usually "closed" with the "COMMIT"
statement, to commit to the database changes that occurred.
4.
If you ran a script that failed, you will find that the part that
"succeeded" prior to the failure will have been committed to
the database. Therefore, the next time you run the script,
you may find a new error message saying that you are trying
to create something that already exists. The solution is to
comment out any statements that have been "passed" on
importing.
5.
4.8 Handling SQL script errors
You import a series of SQL statements into InterBase, typically to
set up Metadata and to insert test data to the Database (How? See
Creating a SQL script). If and when you import a script with Syntax
errors, IBConsole provides you with inadequate error messages.
Throughout this guide are tips to help you avoid error. This section
provides you with the links for information on avoiding and
handling errors on importing.
Create, import and execute a script - see Creating a SQL
script
1.
Error messages for sections that have not previously been2.
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
16 de 42 06/04/2010 18:22
reported - see Creating a SQL script, final paragraph
Unable to connect to the Database - see Creating a SQL
script, CONNECT paragraph
3.
Errors related to end of statements - see Creating a SQL
script, TERMINATIONS paragraph
4.
Corrected errors failing to be picked up by InterBase - If you
amend a text file to correct an error, it is not saved to disk
until you save it. Therefore, remember to save the file
WHENEVER you make any changes. If you have corrected an
error, check the output to confirm which version of the file
InterBase has just tried to import. If is the pre-saved version,
simply save the corrections in your text editor and re-run the
SQL script.
5.
One final point - InterBase identifies where there is an error
by reference to the line count. For this purpose, InterBase
ignores lines without any data. So the 32nd line, is not
necessarily the 32nd line in your file. One solution is to put in
a know error towards the top, run the script and note the line
number of the known error. Keep moving the error down and
re-running the script until you are able to identify the
problem script.
6.
4.9 InterBase Datatypes
There are only a few datatypes within InterBase, and they are
largely instinctive to a Delphi programmer. The InterBase manuals
give the technical specification of different datatype (eg. integer).
There are a couple of datatypes listed below for which you may find
that you may a small amount of guidance saves you a large amount
of time.
Strings - The InterBase equivalent of Strings is VARCHAR(25)
or CHAR(22) . The number in brackets is the number of
characters you want the string to have. A CHAR definition
reserves the number of characters you have specified in the
database, irrespective of the number of characters in the
string (eg. of sql : Name CHAR(50); will allow you to enter
any name up to 50 characters, and InterBase will store 50
characters on disk, even if the name has less characters
(such as 'Smith'). A VARCHAR definition puts an upper limit
on the number of characters you are entitled to save, but will
only use the number of characters in the saved name (5 in
the above example). If you try to put a string with more
characters than the defined field length, the string gets
truncated and you lose the truncated characters.
1.
In earlier versions of InterBase, Floats had a different
concept of decimal point numbers to Delphi. A number was
stored in InterBase with all its decimals, up to the maximum
InterBase can store. If you stored a number, say 4.22, this
was stored within InterBase as 4.2200000012651 (or
something like that). If you stored the result of 4/3, it was
store 1.333333333315561 (or something like that). The
Datatypes available to you affected ONLY the formatting for
display purposes. They ido not affect the storage of the data.
2.
Delphi to InterBase in 15 Minutes file:///C:/Users/TECBMFRP/AppData/Roaming/Mozilla/Firefox/Pro...
17 de 42 06/04/2010 18:22
The two main types of decimal definitions were
NUMERIC(15,2) and DECIMAL(22,5), where the first number
was the length of the number and the second number was
the number of decimal points. The difference between the two
above numbers are subtle and explained in the InterBase
manual - Data definition.
To avoid rounding errors when dealing with currencies, you
had to round any number you wanted to store to 2 decimal
places prior to saving. This prevented the result of storing
'4/3', and adding it to another stored '4/3' from giving you a
result that does not match the displayed sum of '1.33' +
'1.33'.
Under the new versions, the method of storage and
implementation of the number system has changed. For this
reasons, users migrating from earlier versions of InterBase to
version 6 should pay particular attention to the InterBase