3

Most of my application's forms use 2 or more db grids : basically, the user clicks a record in main grid and get child results in a secondary grid.

All my primary DBGrids FDQueries (that is the one with SELECT) have been set on the form but none are "active", they fire on FormShow.

I noticed that, wether I write :

FDQuery1.Active := True;

or

FDQuery1.Open;

the result is the same : my rows are displayed in the main DBGrid.

Accordingly, I call Close or Active := False on FormClose.

But there must be a difference between those approaches and this is the subject of my question : what is the difference between Query.Open and Query.Active := True; ?

What should I use if there is any significant difference ?

Thanks in advance

Math, getting less and less noob as you take the time to answer my questions :)

SIDE NOTE : my INSERT and UPDATE queries are set up with a CLEAR then, SQL.ADD, then Parameters declaration and finally an ExecSQL

whosrdaddy
  • 11,720
  • 4
  • 50
  • 99
Mathmathou
  • 373
  • 4
  • 15
  • 3
    They are the same. The reason you have an Active property is that you can activate the query from within the object inspector at design time. Setting `Active` to True calls internally `Open`. I prefer the `Open/Close` methods because it is very clear what these methods do (code readability). – whosrdaddy Jun 09 '17 at 06:48

2 Answers2

2

Active is a property, Open is a method. When Active is set to true, it calls the Open method, when it is set to false, it calls Close. Active is useful as it can be used to check whether the dataset is actually open.

if Qry.Active then DoSomething;
RED MONKEY
  • 3,025
  • 2
  • 21
  • 23
  • Asking if the query is `Active` and act by that state is a code smell. Though you are correct, the major difference I would pick up here is that `Active` is a published property that can be used at design time, whilst `Open` is a method which can be used only at runtime. I'm for self-descriptive code, so I would personally prefer `Open`/`Close` pair. – Victoria Jun 09 '17 at 20:11
1

SIDE NOTE : my INSERT and UPDATE queries are set up with a CLEAR then, SQL.ADD, then Parameters declaration and finally an ExecSQL

Between Active and Open is no difference.(see whosrdaddy comment) They do the same thing - The dataset becomes active and returns the result from SELECT statement.

You can also use property Active to check if the dataset is active for example:

if not MyQuery.Active then 
  MyQuery.Open; // or MyQuery.Active := true;

ExecSQL execute queries that do not return a cursor to data (such as INSERT, UPDATE, DELETE, and CREATE TABLE).

Val Marinov
  • 2,705
  • 17
  • 22