How to convert between TVarRec and Variant?

Is there a standard way to convert TVarRec and Variant values?

I want to parse the "const array" and use the values ​​to populate the parameters in TMSQuery. To do this, I use a list of column names (generated from TMSQuery.KeyFields) and matching the values ​​in the array with the column names in KeyFields (by position), and then using the column name to set the corresponding parameter using ParamByName.

Below is the code I came up with, but VarRecToVariant does not look very elegant. Is there a better solution?

keyFields: TStringList; // List of table column names (keyFields.DelimitedText := query.KeyFields;) // eg Name, Age query: TMSQuery; // Parametrized query with a parameter for each field in keyFields // SELECT * FROM People WHERE Age=:Age AND Name=:Name // If keyValues is ['Bob', 42] the resulting query should be // SELECT * FROM People WHERE Age=42 AND Name='Bob' procedure Read(keyValues: array of const); var i: Integer; name: string; value: Variant; begin ... for i := 0 to keyFields.Count - 1 do begin name := keyFields[i]; value := VarRecToVariant(keyValues[i]); query.ParamByName(name).Value := value; end; query.Open ... end; function VarRecToVariant(varRec: TVarRec): Variant; begin case varRec.VType of vtInteger: result := varRec.VInteger; vtBoolean: result := varRec.VBoolean; vtChar: result := varRec.VChar; vtExtended: result := varRec.VExtended^; vtString: result := varRec.VString^; ... end; end; 

Notes:

  • The values ​​in the const array depend on the parameters in the request. The caller knows what it is, but the method that uses the array does not know how much or what type to expect. That is, I cannot change the Read method (name: string; age: integer).
  • Parameters are not necessarily used in the same order as the values ​​in the const array. In this example, keyFields are specified as "Name, age", but the request uses Age before Name. This means that Params [i] .Value: = keyValues ​​[i] will not work. I think VarRecToVariant will still be needed, and I try to avoid).
+7
delphi delphi-2006
source share
1 answer

Replace

 procedure Read(keyValues: array of const); 

from

 procedure Read(keyValues: array of Variant); 

Then you will not need to convert TVarRec to Variant.

+5
source share

All Articles