我在使用NodeJS在MySQL表中存储JSON数据时遇到问题。
JSON数据如下所示:
{
"header":
{
"file1":0,
"file2":1,
"subfiles":{
"subfile1":"true",
"subfile2":"true",
}
},
"response":
{
"number":678,
"start":0,
"docs":[
{
"id":"d3f3d",
"code":"l876s",
"country_name":"United States",
"city":"LA"
},
{
"id":"d2f2d",
"code":"2343g",
"country_name":"UK",
"city":"London"
}
]
}
}
我想只存储docs数组(或响应对象)中的字段。 我试图以这种方式获取数据并存储在mysql中:
var express = require('express');
var mysql = require('mysql');
var request = require("request");
var app = express();
app.use('/', express.static('../client/app'));
app.use('/bower_components', express.static('../client/bower_components/'));
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
app.jsonParser = bodyParser.json();
app.urlencodedParser = bodyParser.urlencoded({ extended: true });
//mysql connection setup
var connection = mysql.createConnection({
host : "localhost",
port: "3306",
user : "root",
password : "root",
database : "db",
multipleStatements: true
});
request('http://url.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
//console.log(body) //
}
var data = body.toString();
console.log(string);
var query = connection.query('INSERT INTO table SET ?', data, function(err, result) {
// Finish
});
console.log(query.sql);
});
server.listen(3000, function () {
'use strict';
});
在日志中我得到了
INSERT INTO table SET '{\n \"header\":{\n \"file1\":0,\n \"file2\":1,\n \"subfiles\":{\n \"subfile1\":\"true\",\n \"subfile2\":\"true\"}},\n \"response\":{\"number\":678,\"start\":0,\"docs\":[\n {\n \"id\":\"d3f3d\",\n \"code\":\"l876s\",\n....
输出消息,但我没有MySQL表中的数据。 我是否需要在查询中指定每一列?
答案 0 :(得分:2)
在您的//Finish
评论中,您应该添加一些console.log(err)
,以查看没有插入数据的原因。
这里是解决方案:
var data = JSON.parse(body);
var responseJson = JSON.stringify(data.response);
var query = connection.query('INSERT INTO table SET column=?', responseJson, function(err, result) {
if(err) throw err;
console.log('data inserted');
});