如何在FireDAC中结合SQLite的RETURNING子句使用?
用FireDAC获取SQLite INSERT RETURNING子句返回的值
完全可以通过FireDAC获取SQLite INSERT语句中RETURNING子句返回的自动生成字段值,以下是几种常用的实现方式:
1. 使用ExecSQLScalar获取单个返回值
如果你的RETURNING子句只返回单个字段(比如自增ID),直接用FDConnection的ExecSQLScalar方法最简便,它会直接返回结果集中的第一个值:
var NewRecordID: Integer; begin // 替换为你的表名、字段和参数 NewRecordID := FDConnection.ExecSQLScalar( 'INSERT INTO users(username, email) VALUES(:uname, :umail) RETURNING id', ['johndoe', 'john@example.com'] ); // NewRecordID 就是插入后生成的ID end;
2. 使用TFDQuery获取多字段返回值
如果需要返回多个字段(比如ID、创建时间等),用TFDQuery组件更灵活,执行插入后直接读取结果集即可:
var InsertQuery: TFDQuery; begin InsertQuery := TFDQuery.Create(nil); try InsertQuery.Connection := FDConnection; InsertQuery.SQL.Text := 'INSERT INTO orders(customer_id, total) VALUES(:cid, :total) RETURNING id, order_date, status'; // 设置参数 InsertQuery.ParamByName('cid').AsInteger := 1001; InsertQuery.ParamByName('total').AsFloat := 299.99; // 执行插入并打开结果集 InsertQuery.ExecSQL; InsertQuery.Open; if not InsertQuery.Eof then begin ShowMessage('新订单ID: ' + IntToStr(InsertQuery.FieldByName('id').AsInteger)); ShowMessage('下单时间: ' + InsertQuery.FieldByName('order_date').AsString); end; finally InsertQuery.Free; end; end;
3. 直接用FDConnection的SQLExec配合Query属性
如果你习惯用FDConnection的SQLExec方法,执行后可以通过其内置的Query属性访问返回的结果集:
var NewID: Integer; begin FDConnection.SQL.Text := 'INSERT INTO products(name, price) VALUES(:pname, :price) RETURNING id'; FDConnection.Params.ParamByName('pname').AsString := 'Wireless Headset'; FDConnection.Params.ParamByName('price').AsFloat := 149.99; FDConnection.SQLExec; FDConnection.Query.Open; if not FDConnection.Query.Eof then NewID := FDConnection.Query.FieldByName('id').AsInteger; end;
注意事项
- 确保你的SQLite版本在3.35.0及以上(RETURNING子句从该版本开始支持),同时FireDAC的SQLite驱动要适配对应版本。
- 如果插入多条记录,RETURNING会返回每一条插入记录的对应字段值,此时需要遍历结果集获取所有值。
内容的提问来源于stack exchange,提问作者user3161924
相关产品推荐
相关产品推荐

