Node.js下向MySQL數(shù)據(jù)庫插入批量數(shù)據(jù)的方法
項目(nodejs)中需要一次性插入多筆數(shù)據(jù)到數(shù)據(jù)庫,數(shù)據(jù)庫是mysql的,由于循環(huán)插入的性能太差,就像使用批量插入的方法提高數(shù)據(jù)的插入性能。
批量插入的數(shù)據(jù)庫的表結構如下:

1.數(shù)據(jù)庫連接
var mysql = require('mysql');
// 數(shù)據(jù)庫信息
var connection = mysql.createConnection({
host : 'localhost',
user : '數(shù)據(jù)庫用戶名',
password : '數(shù)據(jù)庫登錄密碼',
database : '操作數(shù)據(jù)庫名'
});
將插入數(shù)據(jù)轉換成嵌套數(shù)組
例如要插入的兩條數(shù)據(jù):
記錄1:
from:"index" to:“www.alibaba.com” status:1 is_new:0
記錄2:
from:"index1" to:"www.google.com" status:1 is_new:0
轉為一下格式:
var values = [ ["index","www.alibaba.com",1,0], ["index1","www.google.com",1,0] ];
編寫插入語句
var sql = "INSERT INTO url(`from`,`to`,`status`, `is_new`) VALUES ?";
調(diào)用query函數(shù)完成數(shù)據(jù)的插入
connection.query(sql, [values], function (err, rows, fields) {
if(err){
console.log('INSERT ERROR - ', err.message);
return;
}
console.log("INSERT SUCCESS");
});
完整代碼:
var mysql = require('mysql');
// 數(shù)據(jù)庫信息
var connection = mysql.createConnection({
host : 'localhost',
user : '數(shù)據(jù)庫用戶名',
password : '數(shù)據(jù)庫登錄密碼',
database : '操作數(shù)據(jù)庫名'
});
var values = [
["index","www.alibaba.com",1,0],
["index1","www.google.com",1,0]
];
var sql = "INSERT INTO url(`from`,`to`,`status`, `is_new`) VALUES ?";
connection.query(sql, [values], function (err, rows, fields) {
if(err){
console.log('INSERT ERROR - ', err.message);
return;
}
console.log("INSERT SUCCESS");
});
同時在這里記錄一個基于事務的操作(還沒有實踐,具體效果不詳)
用事務循環(huán)插入、如果有一條插入失敗進行回滾

mysql模塊、connection.beginTransaction是做事務
然后我這里封裝了一個函數(shù)、對傳入的數(shù)組做循環(huán)插入或更新之類的操作、如果有一條失敗了就回滾、全對了就commit
總結
以上所述是小編給大家介紹的Node.js下向MySQL數(shù)據(jù)庫插入批量數(shù)據(jù),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
MySQL在Linux系統(tǒng)中隱藏命令行中的密碼的方法
這篇文章主要介紹了MySQL在Linux系統(tǒng)中隱藏命令行中的密碼的方法,作者利用簡單的C程序實現(xiàn),需要的朋友可以參考下2015-06-06
數(shù)據(jù)庫中的SELECT語句邏輯執(zhí)行順序分析
這篇文章主要介紹了數(shù)據(jù)庫中的SELECT語句邏輯執(zhí)行順序分析,并列出了一些例子,需要的朋友可以參考下2014-07-07

