简体   繁体   English

MySql LIMIT with express 和 react 时出现 1064 语法错误

[英]MySql 1064 syntax error when LIMIT with express and react

Having a hard time requesting my mysql rows with a limit through the backend.很难通过后端请求我的 mysql 行。

This is my index.js file on my API.这是我的 API 上的 index.js 文件。

app.get("/", (req, res) => {
  return res.send("test");
});
app.get("/Questions", async (req, res) => {
  const questions = await mySqlQuery(
    `SELECT * FROM questions WHERE answer >= :minYear AND answer <= :maxYear ORDER BY RAND() LIMIT :limit;`,
    {
      minYear: req.query.minYear,
      maxYear: req.query.maxYear,
      limit: req.query.limit,
    }
  );
  console.log("Loading question:", req.query);
  return res.json(questions);
});

This is the error这是错误

  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sql: "SELECT * FROM questions WHERE answer >= '-1500' AND answer <= '1500' ORDER BY RAND() LIMIT '5';",
  sqlState: '42000',
  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''5'' at line 1"

Not sure why this happens, If remove the "LIMIT:limit" it works and if I copy the whole string and remove the ` and the: it works in my MySql workbench.不知道为什么会发生这种情况,如果删除“限制:限制”它可以工作,如果我复制整个字符串并删除 ` 和:它可以在我的 MySql 工作台中工作。 I also know that it gets my variable from my client, which in this case is 5.我也知道它从我的客户端获取我的变量,在本例中为 5。

All help appreciated:)所有帮助表示赞赏:)

As @tadman said, simply converting it via parseInt() solves the problem:)正如@tadman 所说,只需通过 parseInt() 进行转换即可解决问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM