Delphi10 如何获取插入 SQLite 的最后一条记录的 ID?
How to get the ID of the last record inserted in SQLite with Delphi 10?
Delphi 10 使用 Firemonkey 和 SQLite:在 运行 下面的代码之后,我想获取插入 SQLite table 的最后一条记录的 ID。我如何获得最后一个 ID?
注意:Table1的ID字段是自增的。
var myQr: TFDQuery;
begin
myQr := TFDQuery.Create(Self);
with myQr do begin
SQL.Add('Insert into table1 values (:_id, :_name, :_dthr)');
Params.ParamByName('_id').ParamType := TParamType.ptInput;
Params.ParamByName('_id').DataType := TFieldType.ftInteger;
Params.ParamByName('_id').Value := null;
ParamByName('_name').AsString := 'name test';
ParamByName('_dthr').AsDateTime := Now;
ExecSQL;
end;
// How to get last ID? <<<<<<<<<<<<<=================
myQr.DisposeOf;
您可以查询last_insert_rowid if your ID column is declared as INTEGER PRIMARY KEY。在这种情况下,该列成为 ROWID 的别名。如果是这种情况,您可以本地查询它,例如这样:
uses
FireDAC.Phys.SQLiteWrapper;
function GetLastInsertRowID(Connection: TFDConnection): Int64;
begin
Result := Int64((TObject(Connection.CliObj) as TSQLiteDatabase).LastInsertRowid);
end;
或通过调用 GetLastAutoGenValue 方法以常用方式:
function GetLastInsertRowID(Connection: TFDConnection): Int64;
begin
Result := Int64(Connection.GetLastAutoGenValue(''));
end;
Delphi 10 使用 Firemonkey 和 SQLite:在 运行 下面的代码之后,我想获取插入 SQLite table 的最后一条记录的 ID。我如何获得最后一个 ID?
注意:Table1的ID字段是自增的。
var myQr: TFDQuery;
begin
myQr := TFDQuery.Create(Self);
with myQr do begin
SQL.Add('Insert into table1 values (:_id, :_name, :_dthr)');
Params.ParamByName('_id').ParamType := TParamType.ptInput;
Params.ParamByName('_id').DataType := TFieldType.ftInteger;
Params.ParamByName('_id').Value := null;
ParamByName('_name').AsString := 'name test';
ParamByName('_dthr').AsDateTime := Now;
ExecSQL;
end;
// How to get last ID? <<<<<<<<<<<<<=================
myQr.DisposeOf;
您可以查询last_insert_rowid if your ID column is declared as INTEGER PRIMARY KEY。在这种情况下,该列成为 ROWID 的别名。如果是这种情况,您可以本地查询它,例如这样:
uses
FireDAC.Phys.SQLiteWrapper;
function GetLastInsertRowID(Connection: TFDConnection): Int64;
begin
Result := Int64((TObject(Connection.CliObj) as TSQLiteDatabase).LastInsertRowid);
end;
或通过调用 GetLastAutoGenValue 方法以常用方式:
function GetLastInsertRowID(Connection: TFDConnection): Int64;
begin
Result := Int64(Connection.GetLastAutoGenValue(''));
end;