【问题标题】:Trying to insert JSON into MySQL with Node.JS尝试使用 Node.JS 将 JSON 插入 MySQL
【发布时间】:2019-05-07 02:41:35
【问题描述】:

使用 Node.JS 我有一个从 API 调用收到的 JSON 输出。我正在尝试将此 JSON 插入 MySQL 但我不断收到错误消息:

“错误:ER_PARSE_ERROR:您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,在第 1 行的“ANU”附近使用正确的语法”

为什么会拒绝输入请求,我该如何纠正?

此外,我宁愿包含多个字段,例如 CountryNameCityName - 我该怎么做?

在 node.JS 中分析 JSON 文件时 console.log(typeof JSON) 返回输出 [object Object]

我认为这是导致上述错误的原因,因为它的格式不正确。

Node.JS 提取:

//MySQL
let con = mysql.createConnection(config);
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected to MySQL!");

  var sql = "INSERT INTO TEST1 (CountryName) VALUES ?";
  var values = obj.LocationsResponse.Country[1].CountryName;
      con.query(sql, values, function (err, result) {
      if (err) throw err;
      console.log("Number of records inserted: " + result.affectedRows);
});
});

JSON 提取(我已经清理以保持简短):

obj = {"LocationsResponse":
{"Country":[
{"CountryName":"United Arab Emirates","CountryCode":"AE","City":[{"CityName":"Abu Dhabi","CityCode":"AUH"},{"CityName":"Dubai","CityCode":"DXB"}]}
,
{"CountryName":"Antigua","CountryCode":"AG","City":{"CityName":"Antigua","CityCode":"ANU"}}
,
{"CountryName":"USA","CountryCode":"US","City":
[{"CityName":"Albuquerque","CityCode":"ABQ",{"CityName":"Albany","CityCode":"ALB",{"CityName":"Amarillo","CityCode":"AMA",
{"CityName":"Anchorage","CityCode":"ANC"
}}}}]} 
]}}

【问题讨论】:

    标签: javascript mysql node.js json parsing


    【解决方案1】:

    JSON 与此错误无关。

    你只是把 INSERT 的语法弄错了。

    你有:

    INSERT INTO TEST1 (CountryName) VALUES ?
    

    你应该有:

    INSERT INTO TEST1 (CountryName) VALUES (?)
    

    MySQL 还支持另一种语法:

    INSERT INTO TEST1 SET CountryName = ?
    

    阅读https://dev.mysql.com/doc/en/insert.html 了解更多关于 MySQL 的 INSERT 语法的信息。

    【讨论】:

    • 谢谢!我现在将阅读此内容。几个小时度过了愉快的时光哈哈。
    猜你喜欢
    • 2019-09-11
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多