可以像这样插入一行:

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')"

我可以使用js字符串操作符手动编译这样的行,但是我需要添加特殊字符.

推荐答案

本文简介:pg-promise library的Performance Boost及其建议方法:

// 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-1

有关通过单个INSERT查询实现的高性能方法,请参见Multi-row insert with pg-promise.

UPDATE-2

这里的信息已经很旧了,请参见Custom Type Formatting的最新语法.以前的_rawDBType现在是rawTypeformatDBType改名为toPostgres.

Postgresql相关问答推荐

Postgs密码重置问题

利用PostgreSQL查询中表的顺序来计算包含每次时间的时间范围

当通过PostgreSQL FDW中的视图使用时,年龄函数的计算方式不同

为什么我的应用程序接收的是空值而不是布尔值?

让Docker Compose Container等待容器PostgreSQL并恢复

在Postgre中的链接服务器上执行远程查询

在 Postgresql 中实现自定义运算符时出错

返回行值和行计数的总和

如何获取在 Go 中完成的 SQL 插入的错误详细信息?

Postgres 将分区附加到表的时间太长.想明白为什么

PostgreSQL 错误:42P01:relation "[Table]" does not exist

Postgres 图像未创建数据库

如何 Select 列值为空的行?

子查询的自连接

从 PostgreSQL 序列中 Select 多个 id

如何正确索引多对多关联表?

PG::ConnectionBad FATAL:role "Myname" does not exist

PostgreSQL 使用 UUID 与文本作为主键

如何使用 PostgreSQL 在任何列中查找所有具有 NULL 值的行

Postgres DB 上的整数超出范围