Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to get JSON object into mysql using node

Tags:

node.js

mysql

Using a prior example? How could I insert/update a mysql table using
a JSON object without manually naming the table column headers? And insure it async.

var mysql = require('node-mysql');
var conn = mysql.createConnection({
    ...
});


var values = [
    {name:'demian', email: '[email protected]', ID: 1},
    {name:'john'  , email: '[email protected]'  , ID: 2},
    {name:'mark'  , email: '[email protected]'  , ID: 3},
    {name:'pete ' , email: '[email protected]'  , ID: 4}
];

// var sql = "INSERT INTO Test (name, email, n) VALUES ?";


   conn.query(sql, [values], function(err) {
        if (err) throw err;
        conn.end();
    })
like image 404
Merlin Avatar asked Mar 12 '13 17:03

Merlin


People also ask

How do I fetch JSON in node JS?

Replicating fetch() with 'node-fetch' package To install, run npm install node-fetch , and set up your code like this: const fetch = require('node-fetch'); let url = "https://www.reddit.com/r/popular.json"; let settings = { method: "Get" }; fetch(url, settings) . then(res => res.


2 Answers

You could do something like this:

for(var i = 0; i < values.length; i++){
    var post  = values[i]
    var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
         // Finish
    });
}

EDIT

This is how you inserts multiple 'posts' at once.

INSERT INTO posts (type, details)
  VALUES
  ('Helen', 24),
  ('Katrina', 21),

You would have to loop through the first value to get the names like this.

var names = [];
for(name in values[0]){
names.push(name);
// That would give you name, email, id
}

Then you would have to create your own string to insert.

var newvalues = [];
for(var i = 0; i < values.length; i++){
    newvalues.push('(' + values[i].join(',') + ')');
}

Then to execute the query:

connection.query('INSERT INTO posts (' + names.join(',') + ') VALUES ' + newvalues.join(',') , function(err, rows, fields) {
  // Result
});

You would have to test the code yourself, this is just how you would do it.

like image 158
Kevin Simper Avatar answered Oct 15 '22 18:10

Kevin Simper


Look at the 'Custom Format' part here. If you notice, this example using named placeholders in the query, allowing you to pass an object, and the placeholders are replaced with the matching attributes from the object. I've also pasted the relevant section for clarity:

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
like image 21
Nick Mitchinson Avatar answered Oct 15 '22 19:10

Nick Mitchinson