下面的示例基于pg-promise库及其方法helpers.update:
// library initialization, usually placed in its own module:const pgp = require('pg-promise')({ capSQL: true // capitalize all generated SQL});const db = pgp();// records to be updated:const updateData = [ {id: 1, value: 1234}, {id: 2, value: 5678}, {id: 3, value: 91011}];// declare your ColumnSet once, and then reuse it:const cs = new pgp.helpers.ColumnSet(['?id', 'value'], {table: 'fit_ratios'});// generating the update query where it is needed:const update = pgp.helpers.update(updateData, cs) + ' WHERe v.id = t.id';//=> UPDATE "fit_ratios" AS t SET "value"=v."value"// FROM (VALUES(1,1234),(2,5678),(3,91011))// AS v("id","value") WHERe v.id = t.id// executing the query:db.none(update) .then(()=> { // success; }) .catch(error=> { // error; });这种生成多行更新的方法可以表征为:
- 非常快,因为它依赖于实现智能缓存以生成查询的ColumnSet类型
- 完全安全,因为所有数据类型都通过库的查询格式引擎来确保所有格式都正确格式化和转义。
- 非常灵活,因为列定义支持高级ColumnConfig语法。
- 由于pg-promise实现了简化的界面,因此非常易于使用。
注意,我们
?在列的前面使用
id以指示该列是条件的一部分,但不进行更新。有关完整的列语法,请参见类Column和ColumnConfig结构。



