【问题标题】:Insert Value in Mysql via node.js通过 node.js 在 Mysql 中插入值
【发布时间】:2013-12-23 23:02:07
【问题描述】:

我使用 Node.js,我想在我的表中插入一些值。

喜欢:

id | profile_id | user_id 
1  |     2      |     7
2  |     2      |     3
3  |     2      |     4 
4  |     2      |     6 

我有一个包含我所有日期(ids)的数组(user_id),我必须在我的数组中做一个 foreach 来插入每个 user_id 值,比如

foreach...
connection.query('INSERT INTO mytable SET ?', my_obj, function(error,risultato) { ...

或者我可以用一个语句在mysql内部做一个循环?

【问题讨论】:

    标签: javascript mysql sql node.js


    【解决方案1】:

    您可以对 MySQL 中的多个 insterts 使用以下语法:

    INSERT INTO mytable (id, profile_id, user_id) VALUES(?,?,?),(?,?,?),(?,?,?);
    

    因此你的代码是:

     connection.query("INSERT INTO mytable (id, profile_id, user_id) VALUES(?,?,?),(?,?,?),(?,?,?)", 
        [id1, profile_id1, user_id1, id2, profile_id2, user_id2, id3, profile_id3, user_id3], 
        function(err, result){ .... });
    

    【讨论】:

    • 我必须做一个 foreach 才能在 INSERT INTO 之前拥有 profile_id1 profile_id2 profile_id3
    • 您不需要 foreach 进行查询。你可能需要它来准备你的数组[id1, profile_id1, user_id1.....
    【解决方案2】:

    在回答@Mustafa 之后我会这样做:(使用sugar.js 和felixge/node-mysql)

    var place ="(";
    rows.each(function(n) {
        columns.add(n.profile_id);
        columns.add(n.user_id);
        columns.add(new Date());
        place += '(?,?,?),';
    });
    
    
    place= place.slice(0,place.lastIndexOf(","));
    
    var sql = 'INSERT INTO mytable (profile_id,user_id,created) VALUES '+place+' ON DUPLICATE KEY UPDATE id=id';
    
    connection.query(sql,
        columns
        , function(error, rows) {
            if (error) {
                var err = "Error on " + error;
                console.dir(err);
                console.log('>>>>>ERROR<<<<< ' + err);
                throw err;
            }
    
            connection.release();
            callback(rows);
    

    希望能帮助到别人

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 2020-11-08
      • 2020-07-18
      • 2017-10-01
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多