欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Node.js下向MySQL數(shù)據(jù)庫插入批量數(shù)據(jù)的方法

 更新時間:2017年10月16日 09:36:46   作者:lym152898  
這篇文章主要介紹了Node.js下向MySQL數(shù)據(jù)庫插入批量數(shù)據(jù)的實現(xiàn)方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下

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

批量插入的數(shù)據(jù)庫的表結(jié)構(gòu)如下:

這里寫圖片描述

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ù)轉(zhuǎn)換成嵌套數(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

轉(zhuǎn)為一下格式:

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

同時在這里記錄一個基于事務(wù)的操作(還沒有實踐,具體效果不詳)

用事務(wù)循環(huán)插入、如果有一條插入失敗進(jìn)行回滾

這里寫圖片描述

mysql模塊、connection.beginTransaction是做事務(wù)

然后我這里封裝了一個函數(shù)、對傳入的數(shù)組做循環(huán)插入或更新之類的操作、如果有一條失敗了就回滾、全對了就commit

總結(jié)

以上所述是小編給大家介紹的Node.js下向MySQL數(shù)據(jù)庫插入批量數(shù)據(jù),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論