9

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: 'demian@gmail.com', ID: 1},
    {name:'john'  , email: 'john@gmail.com'  , ID: 2},
    {name:'mark'  , email: 'mark@gmail.com'  , ID: 3},
    {name:'pete ' , email: 'pete@gmail.com'  , ID: 4}
];

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


   conn.query(sql, [values], function(err) {
        if (err) throw err;
        conn.end();
    })
Merlin
  • 24,552
  • 41
  • 131
  • 206

4 Answers4

6

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.

Kevin Simper
  • 1,669
  • 19
  • 32
  • Can you change the variables to match the questions? – Merlin Mar 18 '13 at 00:20
  • Seem like database is access every time in the loop. Is there a way to only access the database once? A bulk insert? – Merlin Mar 18 '13 at 03:22
  • What about colHeader = Object.keys(values[0]); to get keys? Is there something similar for values? This removes one for loop- well one written for-loop. – Merlin Mar 18 '13 at 18:13
  • @KevinSimper can you please attempt to answer this, it's somehow related but I don't want to get into any kind of loop, just sql statement taking care of everything... http://stackoverflow.com/questions/33003517/mysql-insert-multiple-rows-with-comma-separated-values-with-sql-statement-alone – user2727195 Feb 14 '16 at 05:37
  • @user2727195 Does my answer here solve that for you? – Kevin Simper Feb 16 '16 at 21:48
  • I updated my answer there, instead of loop we can use nested arrays, please check the answer there – user2727195 Feb 17 '16 at 22:21
  • What about escaping the values and add quotes? There has to be a more elegant solution... – Simon Fakir Aug 31 '16 at 21:37
2

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" });
Nick Mitchinson
  • 5,452
  • 1
  • 25
  • 31
0

You could create a small function that maps an array with that format to an insert statement.

You can easily loop through the fields and use some string concatenation.

Evert
  • 93,428
  • 18
  • 118
  • 189
0

Better option is (using MySQL Connection):

app.get('/yourcontroller/:id', function (req, res) {

    var id = req.params.id;
    var dataUpdate = req.body;

    connection.query(
      'UPDATE yourtable SET ? Where ID = ?',
      [dataUpdate, id],
      function (err, result) {
        if (err) throw err;
        console.log('Updated data ! Changed ' + result.changedRows + ' rows');
      }
    );

});