Wenhao Hong
Wenhao Hong

Reputation: 65

Insert JSON object data to MySQL using Node.JS

I want insert a JSON object into MySQL in Node.js server, this is the code

let id = 1
let date = new Date().toJSON().slice(0,10).replace(/-/g,'/');
let sql ='INSERT INTO case_record (case_details,gen_date,case_id) VALUES('+caseDetails+','+date+','+id+')'
console.log(sql)
con.query(sql,function(err, result, fields){
    if(err) throw err;
    res = result;
    console.log(res)
});

This is the caseDetails data

let caseDetails = {
    caseData,
    patData, 
    notifData,
    primecData, 
    refData}

Each of the object in the caseDetails is JSON object also. When I excute, the error return is

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near '[object Object],2019/04/22,1)' at line 1

How to fix this problem?

Upvotes: 2

Views: 5001

Answers (1)

SuperStar518
SuperStar518

Reputation: 2885

Your SQL syntax is wrong to cause parsing error.

Why don't u follow this correction?

...
let sql ='INSERT INTO case_record(case_details,gen_date,case_id) VALUES(?,?,?)';
con.query(sql, [caseDetails,date,id] ,function(err, result, fields) {
  ...
});

Hope to get helped.

Upvotes: 2

Related Questions