简体   繁体   English

将JSON从Node.js存储到SQL Server

[英]Store JSON from Node.js to SQL server

I am extremply new to this kind of development and I am trying to get through this at my best. 我对这种发展非常陌生,我正在努力做到最好。 I am fetching JSON data from my client side, and strying to send these into sql database. 我正在从客户端获取JSON数据,并试图将这些数据发送到sql数据库中。 I am using SSMS 2012. I get an idea of inserting those values (in the code), but what should I do to store these JSON into SQL database? 我正在使用SSMS2012。我有一个想法(在代码中)插入这些值,但是我应该怎么做才能将这些JSON存储到SQL数据库中? Is there any way better than I attempted to do? 有什么方法比我尝试做的更好吗? Below are detail information, please let me know if something is unclear. 以下是详细信息,如果不清楚,请告知我。

JSON JSON格式

{"GradeA":25,"GradeB":36,"GradeC":32} {“ GradeA”:25,“ GradeB”:36,“ GradeC”:32}

sql_Table sql_Table

GradeA | 甲级| GradeB | 乙级| GradeC C级

backend 后端

    app.post('/ping', function (req, res) {
  res.send(res.body);
  var jsondata = JSON.stringify(req.body);
  var test = JSON.parse(jsondata);

  var values = []; 
  values.push(test.GradeA, test.GradeB, test.GradeC)
  console.log(values);

  var dbConn = new sql.Connection(config);

  dbConn.query("INSERT INTO RMS (GradeA, GradeB, GradeC) VALUES ?", [values], function(err, result, fields){
    if (err) throw err;
    //if no error, resulst return as follow
    console.log(result);
    console.log("Number of rows affected :" + result.affectedRows);
    console.log("Number of records affected with warning : " + result.warningCount);
    console.log("Message from MySQL Server : " + result.message);
  });
});

There are several problems with your code. 您的代码有几个问题。

You are using JSON.stringify instead of JSON.parse : 您正在使用JSON.stringify而不是JSON.parse

let json = '{"GradeA":25,"GradeB":36,"GradeC":32}';
let jsondata = JSON.stringify(json);
console.log(typeof jsondata);  // string

let datajson = JSON.parse(json);
console.log(typeof datajson);  // object
console.log(datajson.GradeA);  // 25

Next, it's a really bad idea to make database query in a for loop. 接下来,在for循环中进行数据库查询是一个非常糟糕的主意。

Also note you can't send HTTP response more than once. 还要注意,您不能多次发送HTTP响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM