我在SQL Server中为每个表都有一个记录类型。因此,当我想在表上插入(或更新)记录时,我定义了一个函数来执行此操作。 delphi记录中的每个字段在SQL表中都具有等效字段(具有完全相同的名称和类型)。 对于使用Retti为所有记录类型编写一个函数来执行此操作(例如插入),我感到非常有趣。我的意思是一个函数,它有一个参数来接收任何记录并创建插入查询。 我搜索了很多并问了this问题,但最终找不到解决方案。任何人都可以指导我解决方案。我的意思是如何将任何记录(任何类型)作为参数传递给函数?
答案 0 :(得分:2)
尝试这样的事情:
type
TSqlHlpr<T: record> = class
public
class procedure Insert(const Rec: T);
end;
class procedure TSqlHlpr<T>.Insert(const Rec: T);
var
Ctx: TRttiContext;
RecType: TRttiType;
TableName: String;
Field: TRttiField;
Value: TValue;
FieldValues: TDictionary<String, TValue>;
FieldPair: TPair<String, TValue>;
begin
FieldValues := TDictionary<String, TValue>.Create;
try
Ctx := TRttiContext.Create;
try
RecType := Ctx.GetType(TypeInfo(T));
TableName := RecType.Name;
// massage TableName as needed to match the DB...
for Field in RecType.GetFields do
begin
Value := Field.GetValue(@Rec);
FieldValues.Add(Field.Name, Value);
end;
finally
Ctx.Free;
end;
for FieldPair in FieldValues do
begin
// insert FieldPair.Value into FieldPair.Key column of TableName as needed...
end;
finally
FieldValues.Free;
end;
end;
type
TMyTable = record
// table fields here...
end;
var
rec: TMyTable;
begin
// fill rec as needed...
TSqlHlpr<TMyTable>.Insert(rec);
end;
答案 1 :(得分:0)
好的,我找到了答案。是的,使用类似这样的无类型参数是如此简单:
procedure CreateSQLInsert(var Data)
begin
// and do whatever with your any type record using Retti
end;