使用brianc / node-postgres批量插入Postgres [英] Bulk insert into Postgres with brianc/node-postgres

查看:112
本文介绍了使用brianc / node-postgres批量插入Postgres的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用pg的nodejs中有以下代码( https://github.com/brianc/ node-postgres
我为员工创建订阅的代码就是这样。

I have the following code in nodejs that uses the pg (https://github.com/brianc/node-postgres) My code to create subscriptions for an employee is as such.

    client.query(
      'INSERT INTO subscriptions (subscription_guid, employer_guid, employee_guid) 
       values ($1,$2,$3)', [
        datasetArr[0].subscription_guid,
        datasetArr[0].employer_guid,
        datasetArr[0].employee_guid
      ],


      function(err, result) {
        done();

        if (err) {
          set_response(500, err, res);
          logger.error('error running query', err);
          return console.error('error running query', err);
        }

        logger.info('subscription with created');
        set_response(201);

      });

您已经注意到datasetArr是一个数组。我想一次为多个员工创建大量订阅。但是我不想遍历整个数组。

As you have already noticed datasetArr is an array. I would like to create mass subscriptions for more than one employee at a time. However I would not like to loop through the array. Is there a way to do it out of the box with pg?

推荐答案

我做了一个相同的问题,但是发现了尚无解决方案。
使用异步库,多次使用该查询非常简单,并进行必要的错误处理。

I did a search for the same question, but found no solution yet. With the async library it is very simple to use the query several times, and do the necessary error handling.

此代码变体可能会有所帮助。
(用于将10.000个小的json对象插入到空数据库中需要6秒钟)。

May be this code variant helps. (for inserting 10.000 small json objects to an empty database it took 6 sec).

Christoph

Christoph

function insertData(item,callback) {
  client.query('INSERT INTO subscriptions (subscription_guid, employer_guid, employee_guid)
       values ($1,$2,$3)', [
        item.subscription_guid,
        item.employer_guid,
        item.employee_guid
       ], 
  function(err,result) {
    // return any err to async.each iterator
    callback(err);
  })
}
async.each(datasetArr,insertData,function(err) {
  // Release the client to the pg module
  done();
  if (err) {
    set_response(500, err, res);
    logger.error('error running query', err);
    return console.error('error running query', err);
  }
  logger.info('subscription with created');
  set_response(201);
})

这篇关于使用brianc / node-postgres批量插入Postgres的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆