Parse parameter from SQL query using delphi

How can I parse and retrieve parameters from an SQL query using delphi?

example:

from this request

SELECT * FROM MyTable 
WHERE Field1=:Param1 
AND Field2=:Param2 
AND (Field3=:Param3 OR Field4=:Param4)

I want to receive

Param1 Param2 Param3 Param4

Thanks in advance.

+3
source share
2 answers

@Salvador, you can use the TParams.ParseSQL function to get the parameters.

see this simple code

program Project241;

{$APPTYPE CONSOLE}

uses
  db, //for use TParams
  Classes,// 
  SysUtils;

procedure GetParamsFromSQL(SQL:string;Const ListParams:TStrings);
var
  ParamList: TParams;
  i: integer;
begin
 ListParams.Clear;//Clear the list
    ParamList := TParams.Create(nil);
    try
      ParamList.ParseSQL(SQL, True); //Force to create the params from the SQL
      for i := 0 to ParamList.Count - 1 do 
        ListParams.Add(ParamList[i].Name);
    finally
    ParamList.Free;
    end;
end;

var
  ParamList : TStrings;
begin
  ParamList:=TStringList.Create;
  try
    GetParamsFromSQL('SELECT * FROM MyTable WHERE Field1=:Param1 AND Field2=:Param2 AND (Field3=:Param3 OR Field4=:Param4)',ParamList);
    Writeln(ParamList.text);
    Readln;
  finally
  ParamList.Free;
  end;
end.

returns:

Param1
Param2
Param3
Param4
+10
source

For a simple query like this, you can hack a simple text reading algorithm, as shown below. It works for your specific request, and it can be "good enough." Just go to the empty TStringList.

uses
  StrUtils;

procedure ExtractParams(input: string; output: TStrings);
var
  colon, endpoint: integer;
begin
  colon := pos(':', input);
  while colon <> 0 do
  begin
    input := RightStr(input, length(input) - colon);

    endpoint := 0;
    repeat
      inc(endpoint)
    until input[endpoint] in [' ', ')']; //add other characters here as necessary

    output.Add(LeftStr(input, endpoint - 1));
    colon := pos(':', input);
  end;
end;

SQL, , . GOLD Parser, , SQL, . Delphi -.

0

Source: https://habr.com/ru/post/1739178/


All Articles