咨询TFDCustomQuery类ExecSQL方法中AExecDirect参数的作用
Understanding the
AExecDirect Parameter in TFDCustomQuery.ExecSQL Since the official docs don’t spell this out clearly, let’s break down what this parameter does and when to use each value:
The AExecDirect flag controls whether FireDAC prepares your SQL statement before executing it, or sends it straight to the database server without any pre-processing. Here’s the breakdown:
When AExecDirect = True
- FireDAC skips the statement preparation step entirely and sends the raw SQL to the database.
- Best for: One-off SQL statements that you won’t run again (like a single
DROP TABLE, or a hardcodedUPDATEwith fixed values). - Pros: Saves the small overhead of preparing a statement that you’ll only use once.
- Cons: You can’t use parameterized queries here (since preparation is required for parameter binding). This means you have to manually insert values into the SQL string, which is risky for user input (SQL injection hazard).
When AExecDirect = False (Default)
- FireDAC first prepares the SQL statement: the database parses it, creates an execution plan, and stores it temporarily. Then FireDAC executes the prepared statement.
- Best for: Any SQL you plan to run multiple times with different parameters (like inserting a batch of records, or running the same
SELECTwith varying filters). - Pros:
- Reuses the execution plan for repeated runs, which can boost performance (especially with complex queries).
- Supports parameterized queries, which are secure (prevents SQL injection) and cleaner to write.
- Note: Even if you run the statement only once, using
Falseis safe—FireDAC will clean up the prepared statement automatically after execution unless you explicitly setQuery.Prepared := Trueto keep it around.
Quick Examples
One-off direct execution
var Query: TFDCustomQuery; begin Query := TFDCustomQuery.Create(nil); try Query.Connection := MyFDConnection; Query.SQL.Text := 'DELETE FROM OldRecords WHERE CreatedDate < ''2020-01-01'''; // Execute directly—no preparation needed Query.ExecSQL(True); finally Query.Free; end; end;
Parameterized repeated execution
var Query: TFDCustomQuery; UserID: Integer; begin Query := TFDCustomQuery.Create(nil); try Query.Connection := MyFDConnection; Query.SQL.Text := 'UPDATE Users SET LastLogin = :LoginTime WHERE ID = :UserID'; // Prepare once, execute multiple times for UserID := 1 to 100 do begin Query.ParamByName('LoginTime').AsDateTime := Now; Query.ParamByName('UserID').AsInteger := UserID; Query.ExecSQL(False); end; finally Query.Free; end; end;
Also, keep in mind that the standard ExecSQL overload (without parameters) uses AExecDirect = False under the hood—so if you’re not specifying the parameter, you’re already using prepared statements.
内容的提问来源于stack exchange,提问作者THelloThere
相关产品推荐
相关产品推荐

