使用Node将JSON对象放入mysql的最快方法 [英] Fastest way to get JSON object into mysql using node

查看:133
本文介绍了使用Node将JSON对象放入mysql的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用先前的示例吗?如何使用
插入/更新mysql表 一个JSON对象,而无需手动命名表列标题?并确保它异步.

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();
    })

推荐答案

您可以执行以下操作:

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(',') + ')');
}

然后执行查询:

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.

这篇关于使用Node将JSON对象放入mysql的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆