尝试使用Node.JS将JSON插入MySQL

时间:2019-05-06 18:32:51

标签: javascript mysql node.js json parsing

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

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

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

此外,我希望包含多个字段,例如 CountryName CityName -我该怎么做?

在分析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"
}}}}]} 
]}}

1 个答案:

答案 0 :(得分:0)

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语法的更多信息。