【问题标题】:node PostgresSQL节点 PostgresQL
【发布时间】:2022-01-24 18:00:56
【问题描述】:

我正在尝试查询 postgres 数据库,但我的查询没有返回任何有用的信息。当我不使用参数 sub 即const sql = "SELECT acronym, definition FROM terms WHERE acronym='Thing'" 时它可以工作,但我不确定应该如何完成。我尝试了明显的方法,但没有 bueno。我认为这可能是因为 postgres sql“不支持用于标识的参数”这意味着任何人都知道为什么我的查询不起作用?

app.get("/terms", async (req, res) => {
  let values = req.query.term;
  const sql = "SELECT acronym,definition FROM terms WHERE acronym($1)";
  
  const terms = await pgClient.query(sql, values);

  res.send(terms);
  pgClient.end();
});

工作时

{data: {…}, status: 200, statusText: 'OK', headers: {…}, config: {…}, …}
config: {transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: 'XSRF-TOKEN', adapter: ƒ, …}
data: {command: 'SELECT', rowCount: 46, oid: null, rows: Array(46), fields: Array(2), …}
headers: {access-control-allow-origin: '*', connection: 'keep-alive', content-length: '10023', content-type: 'application/json; charset=utf-8', date: 'Sat, 15 Jan 2022 10:41:45 GMT', …}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
status: 200
statusText: "OK"
[[Prototype]]: Object...

不工作

xhr.js:178 POST http://localhost:8080/api/values 502 (Bad Gateway)
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:59
Promise.then (async)
request @ Axios.js:51
Axios.<computed> @ Axios.js:71
wrap @ bind.js:9
...
xhr.js:178 GET http://localhost:8080/api/terms/all?term=Word 502 (Bad Gateway)

dispatchDiscreteEvent @ react-dom.development.js:4168
createError.js:16 Uncaught (in promise) Error: Request failed with status code 502
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)

【问题讨论】:

    标签: sql node.js reactjs postgresql express


    【解决方案1】:

    关于您的代码的两点说明:

    • values 必须是一个数组,每个参数一个条目
    • 参数在 SQL 查询中显示为 $1, $2, ...(或者,根据数据库,显示为 ?),其他语法没有任何变化。字符串不需要再次引用。
    let values = [req.query.term]; // an array containing the string
    const sql = "SELECT acronym,definition FROM terms WHERE acronym=$1";
    const terms = await pgClient.query(sql, values);
    

    【讨论】:

    • 感谢我的家伙,有时当你凌晨 2 点做这些事情时,你会错过一些小事
    猜你喜欢
    • 2017-12-12
    • 2021-03-25
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多