【发布时间】:2017-05-15 04:19:08
【问题描述】:
Firedac 库集中了数据库行为,并且有很多方法可以正常工作而无需关心数据库类型。实际上,Firedac 使用大多数常见数据库的本地驱动程序,隐藏了语法上的细微差异,允许非常灵活地更改数据库平台。
例如,生成器和 autoinc 字段很容易检测到,CAST 和参数工作正常,允许在数据库之间轻松迁移。
如何在不实例化 FDQuery 的情况下使用 Firedac 功能创建新表,它运行 SQL 脚本 CREATE TABLE?
我希望创建任何对象,并为每个对象字段调用特定的 FieldByName,将其记录在数据库中,但首先我需要证明:
- 如果表已经创建
- 如果字段已创建
- 如果记录已创建
这是我目前拥有的代码:
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 资源的任何数据库执行此操作。
我找到了@Ondrej Kelle 建议的FireDAC.Comp.Client.TFDTable.CreateTable(ARecreate: Boolean = True; AParts: TFDPhysCreateTableParts = [tpTable .. tpIndexes]),但我不明白AParts 的用法。有人有例子吗? http://docwiki.embarcadero.com/Libraries/Berlin/en/FireDAC.Comp.Client.TFDTable.CreateTable
非常感谢。
【问题讨论】:
-
感谢@OndrejKelle,我根据你的建议编辑了这个问题,但我还需要一个例子来做到这一点。
标签: database delphi design-patterns firedac