nodejs mysql批量INSERT在DUPLICATE KEY UPDATE

时间:2017-05-17 13:39:57

标签: mysql node.js

我试图用一个单独的mysql语句插入大约1000行,如果密钥已经存在,则更新该行。

我使用this模块在​​nodejs中执行此操作。

我的代码目前看起来像这样:

this.conn.query("INSERT INTO summoners VALUES ?" +
    " ON DUPLICATE KEY UPDATE name = VALUES(name), rank = VALUES(rank), points = VALUES(points), satisfyCriteria = VALUES(satisfyCriteria), priority = VALUES(priority)," +
    " recentlyChecked = VALUES(recentlyChecked), hotStreak = VALUES(hotStreak), veteran = VALUES(veteran), freshBlood = VALUES(freshBlood), " +
    " wins = VALUES(wins), losses = VALUES(losses)", sql_data, (err) => {
    if( err ){
        logger.error("Error during summoner insert ", err)
    }
    else {
        cb();
    }
})

sql_data是一个嵌套数组。根据libaray的文档:

  

嵌套数组转换为分组列表(对于批量插入),例如   [[' a',' b'],[' c'' d']]变成了(' a&# 39;,' b'),(' c',' d')

因此,我认为这应该可行,但目前我收到此错误

 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 ''Hy Dag3', '55040464', 'master', 114, true, false, false, false, true, false, 34' at line 1

调试sql如下所示:

'INSERT INTO summoners VALUES \'Hy Dag3\', \'55040464\', \'master\', 114, true, false, false, false, true, false, 343, 279 ON DUPLICATE KEY UPDATE name = VALUES(name), rank = VALUES(rank), points = VALUES(points), satisfyCriteria = VALUES(satisfyCriteria), priority = VALUES(priority), recentlyChecked = VALUES(recentlyChecked), hotStreak = VALUES(hotStreak), veteran = VALUES(veteran), freshBlood = VALUES(freshBlood),  wins = VALUES(wins), losses = VALUES(losses)'

这是不正确的。

有人可以帮助我完成这项工作吗?

2 个答案:

答案 0 :(得分:3)

我会尝试一组对象

[
 {name:'Hy Dag3', points:'55040464', rank:'master', hotStreak:114,...},
 {name:'Hkj', points:'554064', rank:'novice', hotStreak:14,...}
]

然后

this.conn.query("INSERT summoners SET ? " +
" ON DUPLICATE KEY UPDATE name = VALUES(name), rank = VALUES(rank)...

因为根据doc:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function (error, results, fields) {
  if (error) throw error;
  // Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'

答案 1 :(得分:3)

尝试将您的sql_data数组数组放入另一个数组中,如此

this.conn.query("...your query", [sql_data], (err) => {...})

所以你在你的陈述中匹配问号,所以如果有另一个问号,它会看起来像[sql_data, another_variable]