我使用 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');
}
- 单独插入的循环是在 Dart postgresql 驱动程序中插入多行的正确方法吗?
- 如果我使用
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
我的代码中的方法?
最佳答案
- 在一个更大的语句中插入多条记录会更高效(来源 https://kaiv.wordpress.com/2007/07/19/faster-insert-for-multiple-rows/ )
多行插入SQL文件
insert into things (thing) values ('thing nr. 0'),
('thing nr. 1'),
('thing nr. 2'),
('thing nr. 3'),
...
('thing nr. 99999),
('thing nr. 100000);
或多个插入语句SQL文件
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);
}
});
而不是
rate.forEach((row) async {
关于postgresql - 如何在 redstone_mapper_pg 中插入多行的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29901327/