使用对象更新准备好的语句
UPDATE prepared statement with Object
我有一个 Object
将列名称映射到值。要更新的列事先未知,在 运行 时间决定。
例如map = {col1: "value1", col2: "value2"}
.
我想执行一个 UPDATE
查询,将那些列的 table 更新为相应的值。我可以执行以下操作吗?如果没有,是否有一种无需手动构建查询的优雅方法?
db.none('UPDATE mytable SET WHERE id = 99', map)
像这样:
map = {col1: "value1", col2: "value2",id:"existingId"}.
db.none("UPDATE mytable SET col1=${col1}, col2=${col2} where id=${id}", map)
is there an elegant way of doing it without building the query manually?
是的,通过使用 helpers 生成 SQL。
您可以像这样预先声明一个静态对象:
const cs = new pgp.helpers.ColumnSet(['col1', 'col2'], {table: 'mytable'});
然后像这样使用它,通过 helpers.update:
const sql = pgp.helpers.update(data, cs) + /* WHERE clause with the condition */;
// and then execute it:
db.none(sql).then(data => {}).catch(error => {})
此方法适用于单个对象和对象数组,您只需相应地附加更新条件即可。
另请参阅:
What if the column names are not known beforehand?
为此,请参阅:,并注意正确的答案将取决于您打算如何转换此类列的类型。
我有一个 Object
将列名称映射到值。要更新的列事先未知,在 运行 时间决定。
例如map = {col1: "value1", col2: "value2"}
.
我想执行一个 UPDATE
查询,将那些列的 table 更新为相应的值。我可以执行以下操作吗?如果没有,是否有一种无需手动构建查询的优雅方法?
db.none('UPDATE mytable SET WHERE id = 99', map)
像这样:
map = {col1: "value1", col2: "value2",id:"existingId"}.
db.none("UPDATE mytable SET col1=${col1}, col2=${col2} where id=${id}", map)
is there an elegant way of doing it without building the query manually?
是的,通过使用 helpers 生成 SQL。
您可以像这样预先声明一个静态对象:
const cs = new pgp.helpers.ColumnSet(['col1', 'col2'], {table: 'mytable'});
然后像这样使用它,通过 helpers.update:
const sql = pgp.helpers.update(data, cs) + /* WHERE clause with the condition */;
// and then execute it:
db.none(sql).then(data => {}).catch(error => {})
此方法适用于单个对象和对象数组,您只需相应地附加更新条件即可。
另请参阅:
What if the column names are not known beforehand?
为此,请参阅: