Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert json data into MariaDB using Nodejs?

I'm inserting JSON data into MariaDB using NodeJs. Getting below error while inserting data. Please advise what cause to get error. Actually Column data1 no empty or null values.Why am i getting below error ?

{ [Error: Column 'data1' cannot be null] code: 1048 }

Table Structure

CREATE TABLE `from_excel` (
    `ID` INT(11) NOT NULL AUTO_INCREMENT,
    `data1` VARCHAR(50) NULL DEFAULT NULL,
    `data2` VARCHAR(100) NULL DEFAULT NULL,
    PRIMARY KEY (`ID`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;

Code which i'm using to insert data.

var Client = require('mariasql');
var c = new Client({
  host     : 'localhost',
  user     : 'xxxx',
  password : 'xxxx',
  db : 'Metrics'
});




const workbook = xlsx.readFile(__dirname + '/test.xlsx');
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
var json=xlsx.utils.sheet_to_json(worksheet);
console.log(json.length);
      for(var i=0;i<json.length;i++)
    {
        var post  = {data1: json[i].data1, data2: json[i].data2};

        var sql = c.query('INSERT INTO elements_from_excel (data1,data2) VALUES (?,?)', post, function(err, result) {
            console.log(sql);
        if(err){console.log(err);}
            else {console.log("success");}

     });

    }
    c.end();
like image 204
user2848031 Avatar asked Jul 17 '26 19:07

user2848031


1 Answers

What could be happening is that the resulting insert statement being run is as follows:

INSERT into from_excel (data1, data2) VALUES (`data1` = \'data1value\', `data2` = \'value\', ?)

Try replacing the query string with the following instead:

var post  = {data1: json[i].data1, data2: json[i].data2};

var sql = c.query('INSERT INTO from_excel SET ?', post, function(err, result) {
            console.log(sql);
        if(err){console.log(err);}
            else {console.log("success");}
like image 117
Nacht Blaad Avatar answered Jul 19 '26 08:07

Nacht Blaad