最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何使用kenxjs在psql中批量插入?

网站源码admin19浏览0评论

如何使用kenxjs在psql中批量插入?

如何使用kenxjs在psql中批量插入?

我搜索了很多东西,这是不建议使用的问题。

我正在尝试批量插入表中。

我的方法就是这样

knex('test_table').where({
  user: '[email protected]',
})
.then(result => {
  knex.transaction(trx => {
    Bluebird.map(result, data => {
      return trx('main_table')
        .insert(data.insert_row)
    }, { concurrency: 3 })
    .then(trxmit);
  })
  .then(() => {
    console.log("done bulk insert")
  })
  .catch(err => console.error('bulk insert error: ', err))
})

如果列在文本或数字列中,但我有jsonb列,则可以使用此方法

所以我收到此错误

json类型的无效输入语法

所以我该如何解决这个问题?

回答如下:

像某些json列之类的声音在发送到数据库时没有字符串化的数据。

这也是插入多行的最慢的方法,因为您要对每个插入的行执行1个查询,并使用单个连接进行插入。

并发3仅使pg驱动程序在与其他所有查询通过同一事务发送给DB之前缓冲这2个查询。

这样的事情应该非常有效(没有测试运行代码,所以可能会有错误):

const rows = await knex('test_table').where({ user: '[email protected]' });
rows.forEach(row => {
  // make sure that json columns are actually json strings
  row.someColumnWithJson = JSON.stringify(row.someColumnWithJson);
});

await knex.transaction(async trx => {
  let i, j, temparray, chunk = 200;

  // insert rows in 200 row batches
  for (i = 0, j = rows.length; i < j; i += chunk) {
    rowsToInsert = rows.slice(i, i + chunk);
    await trx('main_table').insert(rowsToInsert);
  }
});

knex.batchInsert可能对您有用。

发布评论

评论列表(0)

  1. 暂无评论