【问题标题】:Returning Postgres result in nodejs with parameterized query在带有参数化查询的 nodejs 中返回 Postgres 结果
【发布时间】:2021-05-30 00:19:56
【问题描述】:

如何在 Nodejs 中使用参数化查询返回结果?

如果我删除RETURNING*,查询运行良好

现在,服务器返回此错误

错误:“返回”处或附近的语法错误

server.js

const text = "UPDATE users SET info = JSONB_SET(info, '{geometry,coordinates}', '"+coords+"') WHERE id=$1 RETURNING*";
const values = [id];

pool.query(text, values, (err, res) => {

if (err) {

//log errors
console.log(err.stack);

//return error to client

} else {

//success
//console.log(res.rows);


}
});

【问题讨论】:

  • *RETURNING之间不应该有空格吗?
  • @norie : 不,这不会影响查询
  • 我见过的所有使用RETURNING 的查询在RETURNING 之后都有一个空格,后跟* 以返回所有字段或要返回的字段列表。如果后面没有空格,则会被视为RETURNING*
  • @norie :相信我,我试过了。我挠头

标签: node.js postgresql syntax-error node-postgres


【解决方案1】:

要在 node 中使用 postgres 参数化查询,正确的方法是使用 promise 语法。在 Github herehere 上提出了类似的问题。

似乎我在问题中使用的语法的问题在于 pg 正在读取 $1 作为文字字符串的一部分而不是占位符,因为它被包裹在引号中。

Promise 语法似乎正在解决这个问题。好吧,对我有用。

更新查询

const queryOpts = {
text: "UPDATE users SET info = jsonb_set(info, '{geometry,coordinates}', $1) WHERE id = $2",
values: [coords, userid]
}

pool.query(queryOpts).then(response => {
console.log(response.rows)
}).catch(error => {
console.log(error)
})

选择查询

var email = JSON.stringify(logins.email);

const queryOpts = {
text: "SELECT * FROM users WHERE info -> 'email'=$1",
values: [email]
}

pool.query(queryOpts).then(response => {
console.log(response.rows)
}).catch(error => {
console.log(error)
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    相关资源
    最近更新 更多