【问题标题】:How to do a bulk insert with node-postgres如何使用 node-postgres 进行批量插入
【发布时间】:2017-07-17 01:28:15
【问题描述】:

我正在使用 express 和 node-pg 将 excel 文件导入 postgres 数据库

目前我正在遍历 excel 行并为每一行执行插入,但我觉得这不是正确的方法:

workbook.xlsx.readFile(excel_file).then(function () {
        // get the first worksheet          
        var worksheet = workbook.getWorksheet(1);
        // Loop through all rows
        worksheet.eachRow(function (row, rowNumber) {
            // Commit to DB only from line 2 and up. We want to exclude headers from excel file
            if (rowNumber > 1) {
                // Loop through all values and build array to pass to DB function
                row.eachCell(function (cell, colNumber) {
                    arrSQLParams.push(cell.value)                   
                })

                // Add the user id from session to the array
                arrSQLParams.push(user);

                // Insert into DB
                db.query(strSQL, arrSQLParams, function (err, result) {
                    if (err) {
                        console.log(err);
                            ret = false;
                        }
                })

                // Empty the array for new query
                arrSQLParams = [];
            }
        })          
    });

有没有更好的方法来提高性能?

【问题讨论】:

  • 既然您询问性能,您一次可能需要插入的最大行数是多少,以及每行的大致大小?换句话说 - 它是否足够小以一次将所有数据放入 Node.js 内存?
  • 一次大约 1000 行
  • 在这种情况下,最好的方法是通过pg-promise 及其ColumnSet 类型。如果你真的需要,我可以稍后再举一个例子,但基本上都在这里:stackoverflow.com/questions/37300997/…。这正是您同时获得真正出色的性能和灵活性所需要的;)

标签: postgresql express node-postgres


【解决方案1】:

根据作者提供的说明,一次最多插入 1000 条记录,Multi-row insert with pg-promise 中建议的解决方案正是作者所需要的,无论是性能还是灵活性。

更新

必读文章:Data Imports

【讨论】:

    【解决方案2】:

    你可以使用这个包https://www.npmjs.com/package/pg-essential。它将在 node-postgres 上应用补丁,您只需调用它的 executeBulkInsertion 函数。您可以创建要插入的对象数组并将其传递给 执行BulkInsertion 函数。

    let bulkData = [];
    foreach( user in users){
     bulkData.push(user);
    }
    await db.executeBulkInsertion(bulkData,[array of column names],[table name]);
    

    【讨论】:

      猜你喜欢
      • 2014-07-23
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 2018-11-19
      • 2017-09-25
      • 1970-01-01
      相关资源
      最近更新 更多