从Node.js将Json存储到MySQL数据库中 [英] Storing Json into MySQL database from Node.js

查看:341
本文介绍了从Node.js将Json存储到MySQL数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经被问过无数次了,但是经过艰苦的搜索,我似乎找不到要寻找的答案.我有一个* .js格式的脚本,该脚本创建一个json数据数组,然后将其存储在json文件中.

I know this question has been asked numerous times, but after search ferociously, I can not seem to find the answer I am looking for. I have a script in *.js format that creates a json data array then stores it in a json file.

阵列设置为:

var sessionState = {
    currentWalletNdx: 0,
    genesisBlockId: 0,
    genesisBaseTarget: 0,
    genesisBlockTimestamp: 0,
    current: {
        blockHeight: 0,
        baseTarget: 0,
        startTime: 0,
        totalShare: 0,
        submitters: 0,
        bestDeadline: 0,
        totalPayments: 0,
        netDiff: 0
    },
    prevBlocks: []
};

要将数据存储在json文件中,功能是:

And to store the data in a json file the function is:

saveSession: function () {
    var jsonData = JSON.stringify(sessionState, null, 2);
    fs.writeFileSync('pool-session.json', jsonData);
},

我的问题是,如何将其写入此js文件中,以便使用json类型将保存的json数组存储在mysql表中,以便稍后使用php&查看数据. MySQL的?

My question is, how can I write it in this js file to store the saved json array in a mysql table using the json type so I view the data later using php & mysql?

推荐答案

类似的方法应该起作用:

Something like this should work:

var mysql = require('mysql');
var database = mysql.createConnection({
  host: 'host',
  user: 'user',
  password: 'password',
  database: 'database'
});
database.connect(function(connectionError){
  if(connectionError){
    throw connectionError;
  }
  var sql = "INSERT INTO table(column) VALUES ('" + jsonData + "')";
  database.query(sql, function(queryError, queryResult){
    if(queryError){
      throw queryError;
    }
  });
});

将表名称更改为table,将要插入JSON的列名称更改为column.当然,还有数据库连接信息

Change table for the name of your table and column for the name of the column where you want to insert the JSON. And, of course, the database connection information

这篇关于从Node.js将Json存储到MySQL数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆