5

In Delphi, whenever I use a TQuery to perform a SELECT on a database, I follow the Query.Open with a try..finally, with Query.Close in the finally section. This makes sense to me, as the Query would still be storing data (using memory) unnecessarily otherwise.

But my question has to do with when I use a Query to perform an INSERT or DELETE, thus requiring the execution of the SQL with Query.ExecSQL My question is, must I use Query.Close after Query.ExecSQL?

My thoughts are, because this is a command to be executed on the database, which presumably does not return any data to the Query, there is no need to do a Query.Close But maybe someone out there has more in-depth knowledge of what, if anything, might be returned and stored in a Query after a Query.ExecSQL is called, for which a Query.Close would be beneficial?

Thank you.

Paul
  • 25,812
  • 38
  • 124
  • 247
Andrew W
  • 67
  • 1
  • 4
  • It will always return something, rows updated or inserted for example. As far as I can tell you always have to close the Query. – CiucaS Oct 03 '14 at 13:21
  • I never do after an ExecSQL. As you soon as you clear the SQL property, the dataset is closed anyway. I don't think it hurts either way. – J__ Oct 03 '14 at 13:25
  • 2
    `Open` and `Close` are simply alternatives for setting the `Active` property to `True` or `False` respectively. Check the value of `Active` after calling `ExecSQL` and you'll have your answer. – Disillusioned Oct 03 '14 at 13:31

1 Answers1

5

No it is not needed as ExecSQL does not maintain a recordset.

from the documentation (emphasis mine):

Executes the SQL statement for the query. Call ExecSQL to execute the SQL statement currently assigned to the SQL property. Use ExecSQL to execute queries that do not return a cursor to data (such as INSERT, UPDATE, DELETE, and CREATE TABLE).

Note: For SELECT statements, call Open instead of ExecSQL.

ExecSQL prepares the statement in SQL property for execution if it has not already been prepared. To speed performance, an application should ordinarily call Prepare before calling ExecSQL for the first time.

whosrdaddy
  • 11,720
  • 4
  • 50
  • 99