在Delphi XE7中创建任何记录类型的插入函数? [英] Create insert function of any record type in Delphi XE7?

查看:116
本文介绍了在Delphi XE7中创建任何记录类型的插入函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对SQL Server中的每个表都有一个记录类型。因此,当我想在表上插入(或更新)记录时,我定义了一个函数来执行此操作。 delphi记录中的每个字段在SQL表中都有等效的字段(类型完全相同)。
使用Retti为所有记录类型编写一个函数来执行此操作(例如插入),这对我来说太有趣了。我的意思是一个具有用于接收任何记录并创建插入查询的参数的函数。
我进行了很多搜索并询问这个问题,但最终找不到解决方案。谁能指导我解决。我的意思是如何将任何记录(任何类型)作为参数传递给函数?

I have an record type for each Table in SQL Server. So when I want to insert (or update) a record on table I define a function to do so. Each field in delphi record has equivalent field in SQL table (with exact same name an type). It is too interesting to me to write a function to do this ( for example Inserting) for all record types using Retti. I mean a function that have a parameter for receive any record and creates insert query. I searched a lot and asked this question but finally not find the solution. Can anyone guide me to solution. I mean how to pass any record (any type) into a function as parameter?

推荐答案

尝试如下操作:

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;

这篇关于在Delphi XE7中创建任何记录类型的插入函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆