如何解决使用参数化查询在nodejs中返回Postgres结果
如何在 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);
}
});
解决方法
要在 node 中使用 postgres 参数化查询,正确的方法是使用 promise 语法。 Github here 和 here 上也提出了类似的问题。
我在问题中使用的语法的问题似乎是 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)
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。