我是《pg-promise》的作者.
有两种方法可以插入多个记录.第一种也是最典型的方法是通过事务来确保所有记录都正确插入,或者没有插入.
对于pg-promise,可以通过以下方式完成:
db.tx(t => {
const queries = lst.map(l => {
return t.none('INSERT INTO table(id, key, value) VALUES(${id}, ${key}, ${value})', l);
});
return t.batch(queries);
})
.then(data => {
// SUCCESS
// data = array of null-s
})
.catch(error => {
// ERROR
});
使用方法tx启动一个事务,然后创建所有INSERT
个查询promise ,然后将它们全部解析为batch.
第二种方法是将所有插入值连接到一个INSERT
查询中,我将在Performance Boost中详细解释.另见:Multi-row insert with pg-promise.
更多示例请参见Tasks和Transactions.
Addition
值得指出的是,在大多数情况下,我们不会插入记录id
,而是自动生成它.有时我们想拿回新的身份证,而在其他情况下我们不在乎.
根据API,上面的示例使用null
-s数组进行解析,因为batch使用单个结果数组进行解析,而方法none使用null
进行解析.
让我们假设我们想要生成新的id-s,并且我们想要将它们全部取回.为了实现这一点,我们将代码更改为:
db.tx(t => {
const queries = lst.map(l => {
return t.one('INSERT INTO table(key, value) VALUES(${key}, ${value}) RETURNING id',
l, a => +a.id);
});
return t.batch(queries);
})
.then(data => {
// SUCCESS
// data = array of new id-s;
})
.catch(error => {
// ERROR
});
i、 e.这些变化是:
UPDATE-1
有关通过单个INSERT
查询实现的高性能方法,请参见Multi-row insert with pg-promise.
UPDATE-2
必读文章:Data Imports篇.