鍍金池/ 問答/數(shù)據(jù)庫  網(wǎng)絡(luò)安全  HTML/ nodjes讀取csv文件插入mysql操作

nodjes讀取csv文件插入mysql操作

問題描述

前臺上傳文件,后臺用fast-csv模塊讀取文件并插入,希望插入完成以后要返回給前臺,所以采用了promise,但是好像吧并沒有起作用,幾千行會有數(shù)據(jù)沒有插入數(shù)據(jù)庫,大文件會中途停止執(zhí)行,希望能多多指點,謝謝

問題出現(xiàn)的環(huán)境背景及自己嘗試過哪些方法

nodejs的異步執(zhí)行機制,采用過await/async,promise,都不是很管用。

相關(guān)代碼

// 請把代碼文本粘貼到下方(請勿用圖片代替代碼)

//
query2 = (sql, params = []) => {
    return new Promise((resolve, reject) => {
      pool.getConnection((err, connection) => {
        if (err) {
          return reject(err);
        }
        connection.query(sql, params, (err, result) => {
          connection.release();
          if (err) {
            return reject(err);
          }
          resolve(result);
        });
      });
    });
  };
  
  var    sql = "INSERT INTO tf_m_section_number VALUES ?";
  var datas=new Array();
  var pList=new Array();
    fs.createReadStream(fPath)
  .pipe(csv())
  .on("data", function(data){
      counts++;
    if(count<700)
        datas[count++]=data;
    // if(count==3)
    //     console.log(datas);
     if(count==700) {
         console.log(count);
         pList.push(query(sql,[datas]));
        //console.log(result);
        count=0;
        datas.length = 0;
    }
   //  rows[count++]=row;
 })
  .on("end",function(){    
    console.log(counts);
      console.log("done");
    if(count>0){
        pList.push(query(sql,[datas]));
    //    console.log(result);
        //return res.send("ok");
            
    }
    Promise.all(pList).then(function(result) {
        // you code...
        return res.send("ok");
    });
    //
  }).on('error',(err)=>{console.log('讀取文件時發(fā)生異常',err);});

  

你期待的結(jié)果是什么?實際看到的錯誤信息又是什么?

數(shù)據(jù)能全部讀入數(shù)據(jù)庫,事實上會有些數(shù)據(jù)丟失了

回答
編輯回答
尛曖昧

給個思路,把第一遍插入的表復(fù)制一份出來,然后清空原表,再導(dǎo)入一遍,看看前后導(dǎo)入的兩表丟失的數(shù)據(jù):
若丟失的數(shù)據(jù)都是一樣的,那么單獨弄個csv只包含缺失的那部分數(shù)據(jù),再試試導(dǎo)入這份csv,看看報什么錯;
若丟失的數(shù)據(jù)很隨機,那么還需要再具體看看。

2018年7月2日 16:19