How do I do a bulk insert in mySQL using node.js

后端 未结 12 2419
一整个雨季
一整个雨季 2020-11-22 10:39

How would one do a bulk insert into mySQL if using something like https://github.com/felixge/node-mysql

12条回答
  •  独厮守ぢ
    2020-11-22 10:56

    Bulk insert in Node.js can be done using the below code. I have referred lots of blog for getting this work.

    please refer this link as well. https://www.technicalkeeda.com/nodejs-tutorials/insert-multiple-records-into-mysql-using-nodejs

    The working code.

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

    Hope this will help you.

提交回复
热议问题