如何使用 node.js 在 mySQL 中执行批量插入

如果使用类似这样的东西,如何对 mySQL 进行批量插入 Https://github.com/felixge/node-mysql

209851 次浏览

使用嵌套数组可以进行大容量插入,请参见 Github 页面

嵌套数组被转换成分组列表(用于大容量插入) ,例如。 [['a', 'b'], ['c', 'd']]变成 ('a', 'b'), ('c', 'd')

您只需插入一个嵌套的元素数组。

给你中给出了一个例子

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


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

注意: values是一个包装在数组中的数组数组

[ [ [...], [...], [...] ] ]

还有一个完全不同的用于批量插入的 Node-msql

所有的道具都给了 Ragnar123他的回答。

我只是想在 Josh Harington 提出关于插入式身份证的问题后扩展一下。

这些将是连续的。请参阅这个答案: MySQL 多行插入是否抓取顺序自增量 ID?

因此,您可以这样做(请注意我是如何处理 result. insert tId 的) :

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

(我从一个对象数组中提取了这些值,我称之为恒存对象。)

希望这个能帮上忙。

如果 Ragnar的答案对你不起作用。这里可能是原因(根据我的经验)-

  1. 我没有使用我的 Ragnar所示的 node-mysql软件包。我用的是 mysql包。他们是不同的(如果你没有注意到-就像我一样)。但我不确定这是否与 ?不工作有关,因为它似乎对许多人使用 mysql包工作。

  2. 尝试使用一个变量而不是 ?

下面这些对我很有用

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


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

希望这对谁有帮助。

如果需要的话,这里就是我们如何解决数组的插入问题

请求来自邮递员(你会看到“客人”)

 {
"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]
}

还有我们是怎么写剧本的

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

@ Ragnar123的回答是正确的,但是我看到很多人在评论中说它不起作用。我遇到了同样的问题,看起来你需要像这样把你的数组封装在 []中:

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]
];

它需要像 [pars]一样被传递到方法中。

我正在寻找一个关于批量插入对象的答案。

Ragnar123给出的答案让我做出了这个函数:

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

希望能有帮助!

我也有过类似的问题。它只是从数组列表中插入一个。在进行以下更改之后,它工作了。

  1. 传递[ params ]到查询方法。
  2. 将查询从 insert (a,b)更改为 table1值(?)= = > 将(a,b)插入到表1的值中?.也就是说。去掉了问号周围的疑问句。

希望这有帮助。我正在使用 mysql npm。

今天我遇到了这个问题(Mysql2.16.0) ,我想我应该分享一下我的解决方案:

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) => {...}
);

我想提到的几件事情是,我使用 Mysql包与我的数据库建立连接,您在下面看到的是工作代码和为插入批量查询编写的代码。

const values = [
[1, 'DEBUG', 'Something went wrong. I have to debug this.'],
[2, 'INFO', 'This just information to end user.'],
[3, 'WARNING', 'Warning are really helping users.'],
[4, 'SUCCESS', 'If everything works then your request is successful']
];


const query = "INSERT INTO logs(id, type, desc) VALUES ?";


const query = connection.query(query, [values], function(err, result) {
if (err) {
console.log('err', err)
}


console.log('result', result)
});

这是一个快速的“原始复制-粘贴”剪切操作,用于在 mysql 中推送 node.js > = 11的文件列

25万排在几秒钟内

'use strict';


const mysql = require('promise-mysql');
const fs = require('fs');
const readline = require('readline');


async function run() {
const connection = await mysql.createConnection({
host: '1.2.3.4',
port: 3306,
user: 'my-user',
password: 'my-psw',
database: 'my-db',
});


const rl = readline.createInterface({ input: fs.createReadStream('myfile.txt') });


let total = 0;
let buff = [];
for await (const line of rl) {
buff.push([line]);
total++;
if (buff.length % 2000 === 0) {
await connection.query('INSERT INTO Phone (Number) VALUES ?', [buff]);
console.log(total);
buff = [];
}
}


if (buff.length > 0) {
await connection.query('INSERT INTO Phone (Number) VALUES ?', [buff]);
console.log(total);
}


console.log('end');
connection.close();
}


run().catch(console.log);

可以使用下面的代码完成 Node.js 中的大容量插入。为了得到这份工作,我推荐了很多博客。

请参考此连结。 Https://www.technicalkeeda.com/nodejs-tutorials/insert-multiple-records-into-mysql-using-nodejs

工作代码。

  const educations = request.body.educations;
let queryParams = [];
for (let i = 0; i < educations.length; i++) {
const education = educations[i];
const userId = education.user_id;
const from = education.from;
const to = education.to;
const instituteName = education.institute_name;
const city = education.city;
const country = education.country;
const certificateType = education.certificate_type;
const studyField = education.study_field;
const duration = education.duration;


let param = [
from,
to,
instituteName,
city,
country,
certificateType,
studyField,
duration,
userId,
];


queryParams.push(param);
}


let sql =
"insert into tbl_name (education_from, education_to, education_institute_name, education_city, education_country, education_certificate_type, education_study_field, education_duration, user_id) VALUES ?";
let sqlQuery = dbManager.query(sql, [queryParams], function (
err,
results,
fields
) {
let res;
if (err) {
console.log(err);
res = {
success: false,
message: "Insertion failed!",
};
} else {
res = {
success: true,
id: results.insertId,
message: "Successfully inserted",
};
}


response.send(res);
});

希望这个能帮到你。

如果要插入对象,请使用:

    currentLogs = [
{ socket_id: 'Server', message: 'Socketio online', data: 'Port  3333', logged: '2014-05-14 14:41:11' },
{ socket_id: 'Server', message: 'Waiting for Pi to connect...', data: 'Port: 8082', logged: '2014-05-14 14:41:11' }
];


console.warn(currentLogs.map(logs=>[ logs.socket_id , logs.message , logs.data , logs.logged ]));

产出将是:

[
[ 'Server', 'Socketio online', 'Port  3333', '2014-05-14 14:41:11' ],
[
'Server',
'Waiting for Pi to connect...',
'Port: 8082',
'2014-05-14 14:41:11'
]
]

此外,请检查 文件了解更多关于地图功能。

Client.createClient = (clientReqData, result) =>{
var command = 'INSERT INTO client (name,email,phone,country_code,city,state,address,salaes_account_manager,internal_notes) VALUES (?,?,?,?,?,?,?,?,?)' ;
dbConn.query(command,[clientReqData.name,
clientReqData.email,clientReqData.phone,clientReqData.country_code,clientReqData.city,clientReqData.state,clientReqData.address,clientReqData.salaes_account_manager,clientReqData.internal_notes],(err,res)=>{
if(err){
console.log(err)
}else {
client_id = res.insertId;
var command = 'INSERT INTO client_contact_person (name, email ,phone,client_id) VALUES ?';
dbConn.query(command,
[clientReqData.contact.map(item => [item.name, item.email, item.phone,client_id])],
(err, res) => {
if(err) throw err
}
);
result(null,res);
}
})

}

我建议你使用这个专门用于 MySQL 的库,它的用法非常简单。

npm i object_mysql

这将是一个基于2015年1月22日晚上9:39的响应的例子。

import db from 'object_mysql';


const { Test } = await db();


const values = [
{ name:'demian', email:'demian@gmail.com', n:1 },
{ name:'john', email:'john@gmail.com', n:2 },
{ name:'mark', email:'mark@gmail.com', n:3 },
{ name:'pete', email:'pete@gmail.com', n:4 }
];


await Test.add(values);