Cómo hago una inserción masiva en MySQL usando node.js


¿ Cómo se haría una inserción masiva en MySQL si se usa algo como https://github.com/felixge/node-mysql

Author: crickeys, 2012-01-17

8 answers

Las inserciones masivas son posibles mediante el uso de una matriz anidada, consulte la página de github

Los arrays anidados se convierten en listas agrupadas (para inserciones masivas), p.ej. [['a', 'b'], ['c', 'd']] se convierte en ('a', 'b'), ('c', 'd')

Simplemente inserte una matriz anidada de elementos.

Se da un ejemplo en aquí

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

var sql = "INSERT INTO Test (name, email, n) VALUES ?";
var values = [
    ['demian', '[email protected]', 1],
    ['john', '[email protected]', 2],
    ['mark', '[email protected]', 3],
    ['pete', '[email protected]', 4]
];
conn.query(sql, [values], function(err) {
    if (err) throw err;
    conn.end();
});

Nota: values es una matriz de matrices, envueltos en una matriz

[ [ [...], [...], [...] ] ]
 182
Author: Ragnar123,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-10 22:31:13

Todavía no puedo comentar, así que enviaré una respuesta.

@Ragnar123 la respuesta es correcta, pero veo a mucha gente en los comentarios diciendo que no está funcionando. Tuve el mismo problema y parece que necesita envolver su matriz en []

So

 var pars = [
        [99, "1984-11-20", 1.1, 2.2, 200], 
        [98, "1984-11-20", 1.1, 2.2, 200], 
        [97, "1984-11-20", 1.1, 2.2, 200]
      ];

Necesita ser pasado como [pars] en el método.

Espero que esto ayude.

 10
Author: user19,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-16 05:27:34

Todos los apoyos a Ragnar123 para su respuesta.

Solo quería ampliarlo después de la pregunta hecha por Josh Harington para hablar sobre los ID insertados.

Estos serán secuenciales. Ver esta respuesta: ¿Un MySQL multi-fila insertar agarrar secuencial autoincrement IDs?

Por lo tanto, solo puede hacer esto (observe lo que hice con el resultado.insertId):

  var statement = 'INSERT INTO ?? (' + sKeys.join() + ') VALUES ?';
  var insertStatement = [tableName, values];
  var sql = db.connection.format(statement, insertStatement);
  db.connection.query(sql, function(err, result) {
    if (err) {
      return clb(err);
    }
    var rowIds = [];
    for (var i = result.insertId; i < result.insertId + result.affectedRows; i++) {
      rowIds.push(i);
    }
    for (var i in persistentObjects) {
      var persistentObject = persistentObjects[i];
      persistentObject[persistentObject.idAttributeName()] = rowIds[i];
    }
    clb(null, persistentObjects);
  });

(Saqué los valores de una matriz de objetos que llamé persistentObjects.)

Espero que esto ayudar.

 5
Author: thewormsterror,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:06

En caso de que sea necesario aquí es cómo resolvimos insertar de matriz

La solicitud es de cartero (Verá "invitados")

 {
  "author_id" : 3,
  "name" : "World War II",
  "date" : "01 09 1939", 
  "time" : "16 : 22",
  "location" : "39.9333635/32.8597419",
  "guests" : [2, 3, 1337, 1942, 1453]
}

Y cómo escribimos

var express = require('express');
var utils = require('./custom_utils.js');

module.exports = function(database){
    var router = express.Router();

    router.post('/', function(req, res, next) {
        database.query('INSERT INTO activity (author_id, name, date, time, location) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE name = VALUES(name), date = VALUES(date), time = VALUES(time), location = VALUES(location)', 
                [req.body.author_id, req.body.name, req.body.date, req.body.time, req.body.location], function(err, results, fields){
            if(err){
                console.log(err);
                res.json({ status: utils.respondMSG.DB_ERROR });
            }
            else {
                var act_id = results.insertId;
                database.query('INSERT INTO act_guest (user_id, activity_id, status) VALUES ? ON DUPLICATE KEY UPDATE status = VALUES(status)', 
                        [Array.from(req.body.guests).map(function(g){ return [g, act_id, 0]; })], function(err, results, fields){
                    if(err){
                        console.log(err);
                        res.json({ status: utils.respondMSG.DB_ERROR });
                    }
                    else {
                        res.json({ 
                            status: utils.respondMSG.SUCCEED,
                            data: {
                                activity_id : act_id
                            }
                        });
                    }
                });
            }
        });
    });
    return router;
};
 3
Author: Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-22 20:50:57

Estaba buscando una respuesta sobre la inserción masiva de objetos.

La respuesta de Ragnar123 me llevó a hacer esta función:

function bulkInsert(connection, table, objectArray, callback) {
  let keys = Object.keys(objectArray[0]);
  let values = objectArray.map( obj => keys.map( key => obj[key]));
  let sql = 'INSERT INTO ' + table + ' (' + keys.join(',') + ') VALUES ?';
  connection.query(sql, [values], function (error, results, fields) {
    if (error) callback(error);
    callback(null, results);
  });
}

bulkInsert(connection, 'my_table_of_objects', objectArray, (error, response) => {
  if (error) res.send(error);
  res.json(response);
});

Espero que ayude!

 3
Author: Stephen Gibson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-03 22:47:53

Si la respuesta de Ragnar no funciona para ti. Aquí es probablemente por qué (basado en mi experiencia) -

  1. No estaba usando el paquete node-mysql como se muestra en mi Ragnar. Estaba usando el paquete mysql. Son diferentes (por si no te diste cuenta - al igual que yo). Pero no estoy seguro de si tiene algo que ver con el ? no funciona, ya que parecía funcionar para muchas personas que usan el paquete mysql.

  2. Intente usar una variable en lugar de ?

Lo siguiente funcionó para mí -

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

var sql = "INSERT INTO Test (name, email, n) VALUES :params";
var values = [
    ['demian', '[email protected]', 1],
    ['john', '[email protected]', 2],
    ['mark', '[email protected]', 3],
    ['pete', '[email protected]', 4]
];
conn.query(sql, { params: values}, function(err) {
    if (err) throw err;
    conn.end();
});

Espero que esto ayude a alguien.

 1
Author: Aswin Ramakrishnan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-08 00:31:17

Me encontré con esto hoy ( mysql 2.16.0) y pensé en compartir mi solución:

const items = [
    {name: 'alpha', description: 'describes alpha', value: 1},
    ...
];

db.query(
    'INSERT INTO my_table (name, description, value) VALUES ?',
    [items.map(item => [item.name, item.description, item.value])],
    (error, results) => {...}
);
 1
Author: SnobOfTheGolfClub,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-26 22:04:32

Estaba teniendo un problema similar. Solo estaba insertando uno de la lista de matrices. Funcionó después de hacer los siguientes cambios.

  1. Pasó [params] al método de consulta.
  2. Cambió la consulta de insert (a, b) a los valores de table1 (?) = = > insert (a, b) into table1 values ? . IE. Se ha eliminado la parantesis alrededor del signo de interrogación.

Espero que esto ayude. Estoy usando mysql npm.

 0
Author: user1998289,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-06 16:11:46