Author: Fernando Martins
Auxiliary queries built at run time make you copy-paste a lot, replicating your
code. Why not keep it to a minimum, making it easy to read and mantain ?
Do you have an auxiliary TQuery on your form that you use to build dynamic queries,
'SELECT Count(id) FROM Clients'
and a bit latter you use the same TQuery to
'SELECT Count(Phone_numbers) FROM Clients WHERE area = '1''
and latter on you use it again to
'SELECT Count(area) FROM Contacts'
and so on...
If you have an auxiliar TQuery to run all these queries, you probably have a lot of
similar code replicated in your application to load the query string, prepare the
query, run the query and finally close the query.
Since replication is not a good thing when it comes to maintenance, why not
abstract the queries from the code so that you just have to pass the TQuery object,
the query string and, optionally, the database, if you use different databases.
Here's sometinh I've been using for a while that creates that abstraction layer:
2 procedure Execute(Q: TQuery; S: string; DBName = '');
4 with Q do
6 if DBName <> '' then
7 DatabaseName := DBName;
17 while not (Prepared) do
Using this procedure, you can reduce the amount of code and maintenance effort to a
minimum, since you can prepare and open the queries just by using:
26 Execute(MyTQuery, 'SELECT Count(id) FROM Clients');
28 Execute(MyTQuery, 'SELECT Count(Phone_numbers) FROM Clients WHERE area = ' 1 '');
30 Execute(MyTQuery, 'SELECT Count(area) FROM Contacts', 'Contacts_database');
32 Execute(MyTQuery, 'SELECT Count(ZIP) FROM Zip_Codes', 'Address_database');
34 Execute(MyTQuery, 'SELECT Names FROM Vip_Clients', 'clients_database');
After calling the Execute procedure, you are able to read the result from the
TQuery as usual.
This procedure simplifies the process of checking if the object is opened, close it if necessary, prepare the query for execution, release the resources to other processes while not ready and finally run the query.