3
我导入Excel文件,与快递和节点PG如何做节点的Postgres批量插入
目前我通过Excel行循环一个Postgres数据库,并执行插入的每一行,但我觉得它不是正确的方法:
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](https://github.com/vitaly-t/pg-promise)和[ColumnSet](http:/ /vitaly-t.github.io/pg-promise/helpers.ColumnSet.html)类型。如果你真的需要它,我可以在后面举一个例子,但它基本上都在这里:http://stackoverflow.com/questions/37300997/multi-row-insert-with-pg-promise。这就是你需要在同一时间获得非常好的性能和灵活性;) –