mysql 5.6.41 errno 1064:使用变量创建mysql查询

toiithl6  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(257)

我有一个带有express的node.js服务器(目前是localhost,但很快就会通过aws),我正试图通过mysql查询更新一个rds示例,但出现以下错误:

{ [Error: ER_PARSE_ERROR: 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 ''history0' = 'http://localhost:3000/' WHERE id = 1' at line 1]
  code: 'ER_PARSE_ERROR',
  errno: 1064,
  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 \'\'history0\' = \'http://localhost:3000/\' WHERE id = 1\' at line 1',
  sqlState: '42000',
  index: 0,
  sql: 'UPDATE infected SET \'history0\' = \'http://localhost:3000/\' WHERE id = 1;' }

导致错误的post请求:

app.post('/history', function(req, res) {
  var hist = 'history' + 0;
  var sql = 'UPDATE infected SET ? = ? WHERE id = ?;';
  connection.query(sql,  [hist, req.body[0].url, 1]);
});

我在用 hist 作为一个变量,因为我计划把它放在一个循环中,但是我不确定我在这里声明它的方式是否导致了这个问题,所以我把它保持原样。 req.body 是的输出 JSON.stringify() 随叫随到 chrome.history.search() . 因此,我试图获取索引0处条目的url。
我试过直接打电话给 connection.query 硬编码字符串如下:

connection.query("UPDATE infected SET history0='google.com' WHERE id='1'");

而且它成功地更新了数据库,所以我发现在如何使用问号插入变量方面存在问题 hist 以及 req.body[0].url 但我不知道问题出在哪里。

pdsfdshx

pdsfdshx1#

用双“?”键,这样:

app.post('/history', function(req, res) {
  var hist = 'history' + 0;
  var sql = 'UPDATE infected SET ?? = ? WHERE id = ?;';
  connection.query(sql,  [hist, req.body[0].url, 1]);
});

相关问题