node.js를 사용하여 mySQL에서 대량 삽입을 수행하는 방법
https://github.com/felixge/node-mysql 과 같은 것을 사용하는 경우 mySQL에 대량 삽입을 수행하는 방법
중첩 배열을 사용하여 대량 삽입이 가능합니다. github 페이지를 참조하십시오.
중첩 된 배열은 그룹화 된 목록 (대량 삽입 용)
[['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
배열로 래핑 된 배열의 배열입니다.
[ [ [...], [...], [...] ] ]
@ 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);
});
도움이 되었기를 바랍니다.
Ragnar123에 대한 모든 소품.
삽입 된 ID에 대해 Josh Harington이 질문 한 후에 확장하고 싶었습니다.
이들은 순차적입니다. 이 답변을 참조하십시오 : MySQL 다중 행 삽입이 순차적 자동 증가 ID를 가져 옵니까?
따라서이 작업을 수행 할 수 있습니다 (내가 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라고 부르는 객체 배열에서 값을 가져 왔습니다.)
도움이 되었기를 바랍니다.
나는 오늘 ( 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) => {...}
);
여기에 필요한 경우 배열 삽입을 해결하는 방법입니다.
우편 배달부에서 요청한 것입니다 ( "guests"참조).
{
"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;
};
This is a fast "raw-copy-paste" snipped to push a file column in mysql with node.js >= 11
250k row in few seconds
'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);
If Ragnar
's answer doesn't work for you. Here is probably why (based on my experience) -
I wasn't using
node-mysql
package as shown myRagnar
. I was usingmysql
package. They're different (if you didn't notice - just like me). But I'm not sure if it has anything to do with the?
not working, since it seemed to work for many folks using themysql
package.Try using a variable instead of
?
The following worked for me -
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();
});
Hope this helps someone.
Few things I want to mention is that I'm using mysql package for making a connection with my database and what you saw below is working code and written for insert bulk query.
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)
});
I was having similar problem. It was just inserting one from the list of arrays. It worked after making the below changes.
- Passed [params] to the query method.
- Changed the query from insert (a,b) into table1 values (?) ==> insert (a,b) into table1 values ? . ie. Removed the paranthesis around the question mark.
Hope this helps. I am using mysql npm.
참고URL : https://stackoverflow.com/questions/8899802/how-do-i-do-a-bulk-insert-in-mysql-using-node-js
'development' 카테고리의 다른 글
C 빅 엔디안 또는 리틀 엔디안 머신을 결정하는 매크로 정의? (0) | 2020.08.15 |
---|---|
어떤 요소를 클릭하든 WPF 창을 드래그 가능하게 만듭니다. (0) | 2020.08.15 |
C ++, 'if'표현식의 변수 선언 (0) | 2020.08.15 |
어셈블리 오류에서 유형을로드 할 수 없습니다. (0) | 2020.08.15 |
ORM을 사용하지 않는 이유가 있습니까? (0) | 2020.08.15 |