使用没有 SQL 脚本的 firedac 创建 table

Create table with firedac without SQL Script

Firedac 库集中了数据库行为,并且有很多方法可以在不关心数据库类型的情况下正常工作。实际上,Firedac 使用大多数常见数据库的本机驱动程序,隐藏了语法上的细微差异,允许非常灵活地更改数据库平台。
例如,生成器和 autoinc 字段很容易检测到,CAST 和参数工作正常,允许在数据库之间轻松迁移。

如何在不实例化 FDQuery 的情况下使用 Firedac 功能创建新的 Table,它运行 SQL 脚本 CREATE TABLE?

我希望创建任何对象,并为每个对象字段调用特定的 FieldByName,将其记录在数据库中,但首先我需要证明:

  1. 如果 Table 已经创建
  2. 如果字段已经创建
  3. 如果记录已创建

这是我目前拥有的代码:

TRecCustomer = record
  Id:integer;
  Name:String;
  Birthday:TDate;
end;

ICustomer = interface
  procedure setCustomerId(Value: Integer);
  procedure setCustomerName(Value: String);
  procedure SetBirthday(Value: TDate);
  procedure Post;
end;

TCustomer = class(TInterfacedObjet, ICustomer)
  CustomerObject=TRecCustomer;

  procedure setCustomerId(Value: Integer);
  procedure setCustomerName(Value: String);
  procedure SetBirthday(Value: TDate);
  procedure Post;
end;

procedure TCustomer.Post;
begin
  if not TableExists('Customer') then CreateTable('Customer');
  if not FieldExists('Name') then CreateField('Customer','name',ftString,[],40);
  if not FieldExists('Id') then CreateField('Customer','Id',ftInteger,[cAutoInc,cNotNull]);
  if not FieldExists('Birthday') then CreateField('Customer','birthday',ftDate);
end;

想象程序

CreateTable(Tablename: String)
CreateField(FieldName: String; FieldType: TDataType; Constraints: TConstraints; Length: Integer = 0);

哪里

TConstraints = set of (cAutoInc, cNotNull, cUnique, cEtc);

我可以针对特定数据库执行此操作,例如 Sqlite 或 Firebird,但我不知道如何针对使用 Firedac 资源的任何数据库执行此操作。


我找到了 FireDAC.Comp.Client.TFDTable.CreateTable(ARecreate: Boolean = True; AParts: TFDPhysCreateTableParts = [tpTable .. tpIndexes]),@Ondrej Kelle 建议,但我不明白 AParts 的用法。有人有例子吗? http://docwiki.embarcadero.com/Libraries/Berlin/en/FireDAC.Comp.Client.TFDTable.CreateTable

非常感谢。

您可以创建一个 TFDTable object, describe your table at least by specifying TableName and adding field definitions in the FieldDefs collection. In practice you'll usually create also a primary key index for some field (that's what can be done by the AddIndex method). After you describe your table, call CreateTable 方法。一个最小的例子可以是:

var
  Table: TFDTable;
begin
  Table := TFDTable.Create(nil);
  try
    Table.Connection := FDConnection1;
    { specify table name }
    Table.TableName := 'MyTable';
    { add some fields }
    Table.FieldDefs.Add('ID', ftInteger, 0, False);
    Table.FieldDefs.Add('Name', ftString, 50, False);
    { define primary key index }
    Table.AddIndex('pkMyTableID', 'ID', '', [soPrimary]);
    { and create it; when the first parameter is True, an existing one is dropped }
    Table.CreateTable(False);
  finally
    Table.Free;
  end;
end;