如何在NodeJS上将JSON数据写入MySql数据库?

时间:2015-09-17 01:20:34

标签: mysql json database node.js firebird2.5

我有JSON数据,这是我从Firebird数据库获得的。现在,我想创建mysql连接并将JSON数据写入NodeJS上的MySql数据库。但是当我关闭Firebird连接并创建MySql连接并对其进行一些查询时,它会出错:

  

events.js:85         扔掉//未处理的错误'事件               ^   错误:调用退出后无法排队握手。       在Protocol._validateEnqueue(/Users/myuser/node_modules/mysql/lib/protocol/Protocol.js:196:16)       在Protocol._enqueue(/Users/myuser/node_modules/mysql/lib/protocol/Protocol.js:129:13)       在Protocol.handshake(/Users/myuser/node_modules/mysql/lib/protocol/Protocol.js:52:41)       在Connection.connect(/Users/myuser/node_modules/mysql/lib/Connection.js:123:18)       在服务器上。 (/Users/myuser/Documents/project/convert_fdb_to_mysql.js:34:14)       在Server.emit(events.js:110:17)       在HTTPParser.parserOnIncoming [as oncoming](_http_server.js:491:12)       在HTTPParser.parserOnHeadersComplete(_http_common.js:111:23)       在Socket.socketOnData(_http_server.js:343:22)       在Socket.emit(events.js:107:17)

我想修复此错误并将我的JSON写入MySql数据库。 你能告诉我怎样才能解决我的问题?

有关将JSON数据传输到MySql数据库的任何建议吗?

谢谢,

这是我从Firebird db获取数据的代码:

var fb = require('firebird');
var util = require('util');
var http = require('http');
// mySQL connection
var mysql = require('mysql');
var connection = mysql.createConnection({
    socketPath: '/tmp/mysql.sock',
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'mysql_db'
});
http.createServer(function (req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/plain'
    });
    // Firebird connection
    var con = fb.createConnection();
    con.connectSync('FIREBIRD.FDB', 'SYSDBA', 'masterkey', '');
    var rs = con.querySync('SOME SQL Query');
    var rows = rs.fetchSync("all", true);
    con.disconnect(); // Firebird disconnect
    connection.connect(); // mysql connect
    connection.query('SOME SQL Query', function (err, rows, fields) {
        if (err) throw err;
        console.log(rows[0]);
    });
    connection.end(); // mysql disconnect
    res.write('[');
    rows.forEach(function (r) {
        res.write(JSON.stringify(r) + ',');
    });
    res.end(']');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');

1 个答案:

答案 0 :(得分:0)

此方法有效! https://stackoverflow.com/a/14247110/5344483

对于JSON到MySql:

Write queries with "JSON.stringify(r.FIELD_NAME)"