Delphi: how to pass a list as a parameter to a SQL query?

前端 未结 7 733
你的背包
你的背包 2020-12-17 16:44

I have a list of integers or of strings and need to pass it as a parameter for a Delphi DataSet. How to do it?

Here is an example. MyQuery is something like:

相关标签:
7条回答
  • 2020-12-17 17:11

    SQL accepts only single values as parameters so you cannot create a statement with one parameter that can map to a variable number of values, such as the example you gave.

    However, you can still use parameterized SQL in this situation. The solution is to iterate over the list of values you have, adding a parameter marker to the SQL and a parameter to the parameter list for each value.

    This is easiest to do with positional rather than named parameters but can be adapted for named parameters as well (you may need to adjust this code since I don't have Delphi available and don't remember the Parameter creation syntax):

     //AValues is an array of variant values
     //SQLCommand is some TDataSet component with Parameters.
     for I := Low(AValues) to High(AValues) do
     begin
    
        if ParamString = '' then
           ParamString = '?'
        else
          ParamString = ParamString + ', ?';
    
        SQLCommand.Parameters.Add(AValues[I]);
    
      end
    
      SQLCommand.CommandText = 
         'SELECT * FROM MyTable WHERE KeyValue IN (' + ParamString + ')';
    

    This will produce an injection-safe parameterized query.

    0 讨论(0)
提交回复
热议问题