Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

48
Views
how to insert array of data per column in MySQL?

I have arrays stacked in 1 array and I would like to insert each array per column in MySQL. I have reached to insert all data in arrays to 1 column, but I want to insert an array per column. Please see the screenshot and code below.

Image of array stack

con.connect(async(err)=>{
  const x = await getStock()
  if(err){
      console.log(err);
      return err;
  }else{
      console.log("DB ok");
  }
  console.log("connected");
  x.filter(item=>item===undefined?false:true).map(item=>item.forEach(item=>{
    const sql ="INSERT INTO test (testCol1) VALUES ?";
    const values=[
      [item]
    ];
    con.query(sql,[values],(err,result)=>{
      if(err)throw err;
      console.log("this have been recorded"+result);
    });
  }));
});
7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

I just found a solution for this case. It can be a little bit confusing but it is working. Maybe there exists way easier and understandable solution, but this is the solution I have at the moment.

In the code above I was using only 1 array iterator, which was returning me an array. I decided to iterate the returned array to get each integer and insert data into MySQL, also the (test${i+1}) sets array into necessary column.

  x.filter(item=>item===undefined?false:true).forEach((item,i)=>{
    item.forEach(item=>{
      const sql =`INSERT INTO test (test${i+1}) VALUES ?`;
      const values=[
        [item]
      ];
      con.query(sql,[values],(err,result)=>{
        if(err)throw err;
        console.log("this have been recorded"+result);
      });
    })
  });
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs