如果使用类似的东西,如何批量插入mySQL? https://github.com/felixge/node-mysql
答案 0 :(得分:218)
使用嵌套数组可以进行批量插入,请参阅github page
嵌套数组转换为分组列表(对于批量插入),例如
[['a', 'b'], ['c', 'd']]
变为('a', 'b'), ('c', 'd')
您只需插入嵌套的元素数组。
中给出了一个例子var mysql = require('node-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
是一个包含在数组中的数组数组
[ [ [...], [...], [...] ] ]
答案 1 :(得分:14)
@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]
一样传递给方法。
答案 2 :(得分:8)
我正在寻找有关批量插入对象的答案。
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);
});
希望它有所帮助!
答案 3 :(得分:6)
所有支持Ragnar123的道具都是他的答案。
我只是想在Josh Harington提出的问题之后扩展它,讨论插入的ID。
这些将是连续的。请参阅此答案:Does a MySQL multi-row insert grab sequential autoincrement IDs?
因此你可以这样做(注意我对result.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);
});
(我从一个名为persistentObjects的对象数组中提取了值。)
希望这有帮助。
答案 4 :(得分:4)
我今天遇到了这个问题(mysql 2.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) => {...}
);
答案 5 :(得分:3)
如果这里需要的是我们如何解决数组的插入
请求来自邮递员(您将看到&#34;来宾&#34;)
{
"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;
};
答案 6 :(得分:1)
如果Ragnar
的答案对您不起作用。这可能是为什么(根据我的经验) -
我没有使用node-mysql
包,如Ragnar
所示。我正在使用mysql
包。他们是不同的(如果你没有注意到 - 就像我一样)。但我不确定它是否与?
无效有关,因为它似乎适用于使用mysql
包的许多人。
尝试使用变量而不是?
以下对我有用 -
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();
});
希望这有助于某人。
答案 7 :(得分:1)
我想说的几件事是,我正在使用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)
});
答案 8 :(得分:0)
我遇到了类似的问题。它只是从数组列表中插入一个。它在进行了以下更改后起作用。
希望这会有所帮助。我正在使用mysql npm。
答案 9 :(得分:0)
这是一个快速的“原始复制粘贴”,可通过node.js> = 11推送到mysql中的文件列
在几秒钟内达到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);
答案 10 :(得分:0)
可以使用下面的代码批量插入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);
});
希望这会对您有所帮助。
答案 11 :(得分:0)
如果要插入对象,请使用此:
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'
]
]
另外,请检查documentation进一步了解地图功能。
答案 12 :(得分:0)
就所有答案而言,使用像 toff 这样的数组的解决方案之一:
var values = [
['demian', 'demian@gmail.com', 1],
['john', 'john@gmail.com', 2],
['mark', 'mark@gmail.com', 3],
['pete', 'pete@gmail.com', 4]];
<块引用>
不工作
...适用于所有情况,特别是大型插入查询。
<块引用>以下解决方案适用于所有情况:
var sql0 = "insert into tblname (fld1,fld2,fld3) values";
var sql1 = "('" + vala1 + "','" + vala2 + "','" + vala3 + "')";
var sql2 = "('" + valb1 + "','" + valb2 + "','" + valb3 + "')";
var sql3 = "('" + valc1 + "','" + valc2 + "','" + valc3 + "')";
var sql4 = sql0 + sql1 + "," + sql2 + "," + sql3 + ";";
con.query(sql4, function (err, result) {
if (err) throw err;
//do somthing...
});