如何使用 node-postgres 将多行正确插入 PG?

新手上路,请多包涵

可以像这样插入单行:

 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 字符串运算符手动编译这些行,但是我需要以某种方式添加特殊字符转义。

原文由 stkvtflw 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 980
2 个回答

在这篇文章之后: pg-promise 库的 性能提升 及其建议的方法:

 // 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
    });

更新-1

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

更新-2

这里的信息现在已经很老了,请参阅 Custom Type Formatting 的最新语法。以前的 _rawDBType 现在是 rawType ,而 formatDBType 更名为 toPostgres

原文由 vitaly-t 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用以标记模板字符串为核心的 npm 模块 postgres ( porsager/postgres ):

https://github.com/porsager/postgres#multiple-inserts-in-one-query

 const users = [{
  name: 'Murray',
  age: 68,
  garbage: 'ignore'
},
{
  name: 'Walter',
  age: 80,
  garbage: 'ignore'
}]

sql`insert into users ${ sql(users, 'name', 'age') }`

// Is translated to:
insert into users ("name", "age") values ($1, $2), ($3, $4)

// Here you can also omit column names which will use all object keys as columns
sql`insert into users ${ sql(users) }`

// Which results in:
insert into users ("name", "age", "garbage") values ($1, $2, $3), ($4, $5, $6)

只是想我会发布,因为它就像全新的测试版,我发现它是 SQL 库的更好哲学。我认为比其他答案中发布的其他 postgres/node 库更可取。恕我直言

原文由 700 Software 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题