我使用redstone_mapper_pg,我需要在数据库表中插入许多行:
class Rate {
@Field() String zone_id;
@Field() String cost;
}
@app.Route("/rplan", methods: const [app.POST])
addRPlan(@Decode() List<Rate> rate) async {
try {
await pgsql.execute('begin');
rate.forEach((row) async {
try {
await pgsql.execute('insert into t_rate (zone_id,cost) '
'values (@zone_id,@cost)', row);
} catch(err) {
await pgsql.execute('rollback');
return new Future.error(err);
}
});
} catch(err) {
await pgsql.execute('rollback');
return new Future.error(err);
}
await pgsql.execute('end');
return new Future.value('OK');
}
rate.forEach((row) async {
我的执行链 begin-end-insert-insert 错误,因为.forEach
方法异步调用参数函数。 rate.forEach(await (row) async {
也是如此。使用await rate.forEach(await (row) async {
给出右链 begin-insert-insert-end ,但插入是相对于 begin-end 异步执行的。只有标准for(int i=0; i<rate.length; i++) {
循环才能提供所需的结果。有没有办法在我的代码中使用.forEach
方法?答案 0 :(得分:2)
多行插入SQL文件
$finish
或多个插入语句SQL文件
insert into things (thing) values ('thing nr. 0'),
('thing nr. 1'),
('thing nr. 2'),
('thing nr. 3'),
...
('thing nr. 99999),
('thing nr. 100000);
begin;
insert into things (thing) values ('thing nr. 0');
insert into things (thing) values ('thing nr. 1');
insert into things (thing) values ('thing nr. 2');
....
insert into things (thing) values ('thing nr. 99999');
insert into things (thing) values ('thing nr. 100000');
commit;
而不是
await for(row in rate) {
try {
await pgsql.execute('insert into t_rate (zone_id,cost) '
'values (@zone_id,@cost)', row);
} catch(err) {
await pgsql.execute('rollback');
return new Future.error(err);
}
});