是否有标准方法在TVarRec和Variant值之间进行转换?
我想解析'const数组'并使用这些值来填充TMSQuery中的参数。为此,我使用列名列表(从TMSQuery.KeyFields生成),并将数组中的值与KeyFields中的列名匹配(按位置),然后使用列名称使用ParamByName设置相应的参数
以下代码是我提出的,但VarRecToVariant似乎并不优雅。有更好的解决方案吗?
keyFields: TStringList;
// List of table column names (keyFields.DelimitedText := query.KeyFields;)
// e.g. 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;
注意:
答案 0 :(得分:5)
替换
procedure Read(keyValues: array of const);
与
procedure Read(keyValues: array of Variant);
然后您不需要将TVarRec转换为Variant。