postgresql - 如何在 redstone_mapper_pg 中插入多行的正确方法?

标签 postgresql asynchronous dart

我使用 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');
}
  1. 单独插入的循环是在 Dart postgresql 驱动程序中插入多行的正确方法吗?
  2. 如果我使用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我的代码中的方法?

最佳答案

  1. 在一个更大的语句中插入多条记录会更高效(来源 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/

    相关文章:

    java - Hibernate 有时会在子实体中留下空的外键字段

    c++ - QML TableView + PostgreSQL 数据库报错

    node.js - Node 在插入之前关闭数据库连接或根本不关闭

    dart - 扩展PaperDialog并通过Dart调用toggle()

    android - 如何创建自定义堆栈中的条子出现在 flutter 中?

    dart - 在 dart 中向 int 添加点

    php - 从不同主机将数据从 Postgresql 传输到 Mysql(从 RoR 数据库到 Wordpress 数据库)

    sql - 将两个 SELECT 查询合并为一个

    asynchronous - 将 Either 与 Future 一起使用

    javascript - 当方法可能会或可能不会异步获取数据时,应使用哪种 RxJS 类型?