如何使用node-postgres进行批量插入

Fab*_*oni 7 postgresql express node-postgres

我正在使用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 = [];
            }
        })          
    });
Run Code Online (Sandbox Code Playgroud)

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

vit*_*y-t 6

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

更新

必读文章:数据导入