我如何正确地插入多个行与PG节点postgres?

单行可以像这样插入:

client.query("insert into tableName (name, email) values ($1, $2) ", ['john', 'john@gmail.com'], callBack) 

这种方法自动评论任何特殊字符。

我如何一次插入多行?

我需要实现这个:

 "insert into tableName (name, email) values ('john', 'john@gmail.com'), ('jane', 'jane@gmail.com')" 

我可以只使用jsstring运算符手动编译这样的行,但是我需要添加特殊字符转义莫名其妙。

本文后面的内容:来自pg-promise库的Performance Boost及其build议的方法:

 // Concatenates an array of objects or arrays of values, according to the template, // to use with insert queries. Can be used either as a class type or as a function. // // template = formatting template string // data = array of either objects or arrays of values function Inserts(template, data) { if (!(this instanceof Inserts)) { return new Inserts(template, data); } this._rawDBType = true; this.formatDBType = function () { return data.map(d=>'(' + pgp.as.format(template, d) + ')').join(','); }; } 

一个使用它的例子,就像你的情况一样:

 var users = [['John', 23], ['Mike', 30], ['David', 18]]; db.none('INSERT INTO Users(name, age) VALUES $1', Inserts('$1, $2', users)) .then(data=> { // OK, all records have been inserted }) .catch(error=> { // Error, no records inserted }); 

它也将与一系列对象一起工作:

 var users = [{name: 'John', age: 23}, {name: 'Mike', age: 30}, {name: 'David', age: 18}]; db.none('INSERT INTO Users(name, age) VALUES $1', Inserts('${name}, ${age}', users)) .then(data=> { // OK, all records have been inserted }) .catch(error=> { // Error, no records inserted }); 

UPDATE

对于通过单个INSERT查询的高性能方法,请参阅使用pg-promise的多行插入 。

 client.query("insert into tableName (name, email) values ($1, $2),($3, $4) ", ['john', 'john@gmail.com','john', 'john@gmail.com'], callBack) 

不帮忙? 而且,您可以手动为查询生成一个string:

 insert into tableName (name, email) values (" +var1 + "," + var2 + "),(" +var3 + ", " +var4+ ") " 

如果你在这里阅读, https://github.com/brianc/node-postgres/issues/530 ,你可以看到相同的实现。

另一种使用PostgreSQL json函数的方法是:

 client.query('INSERT INTO table (columns) ' + 'SELECT m.* FROM json_populate_recordset(null::your_custom_type, $1) AS m', [JSON.stringify(your_json_object_array)], function(err, result) { if(err) { console.log(err); } else { console.log(result); } });