MySQL 5.6.41 错误号 1064 : Creating a MySQL query with variables

标签 mysql node.js express

我有一个(当前是 localhost,但很快将通过 AWS)带有 Express 的 Node.JS 服务器,当我收到以下错误时,我正在尝试通过 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 是在调用 chrome.history.search() 时调用的 JSON.stringify() 的输出。所以我试图获取索引 0 处的条目的 URL。

我尝试使用硬编码字符串直接调用connection.query,如下所示:

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

它成功更新了数据库,所以我认为我如何使用问号插入变量 histreq.body[0].url 进入查询,但我无法弄清楚问题是什么。

最佳答案

尝试使用双“??”对于 key ,这样:

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]);
});

关于MySQL 5.6.41 错误号 1064 : Creating a MySQL query with variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53551232/

相关文章:

php - 建立多向关系数据库并收集表单数据

c# - sql 不适用于特定查询 C#

node.js - 带 Node 的Nginx服务器返回js代码

node.js - Express 请求对象未正确报告 https

node.js - nodejs - 表达如何在所有路由上创建全局变量?

php - 获取免费IP地址的算法

mysql - 从数据库查询中获取满足状态和 id 的间隔为 1 天的日期

javascript - 在 Node.js 中写入文件

JavaScript 大整数平方根

mysql - 触发级联DELETE,不删除记录