1

I am working on nodejs for the first time. I have a scenario where I am having json array like shown below. I will not know how many json items will be there in that array.

I have tried solution using loops but it will fire the query for multiple times. And I don't want that.

{"qualification":[{"degreeName":"B","domain":"p"},{"degreeName":"A","domain":"q"}]}

And mysql query will be like this

INSERT INTO qualification (degreeName,domain) VALUES (B,p),(A,q);

In the above query I have explicitly written values, but as I will not know how many values will be there I can't write values like that, instead i will have to put all values in a variable and then pass it to the query. So how can I retrive and convert qualification data into varible or tuples to put into mysql query so that I can fire single query and add multiple values.

1 Answer 1

4

You could do something like this: You'll have to generate values array from dynamic values and pass onto the query.

Key point: ? is a unnamed parameter (placeholder alias) to make it Parameterised Query

const mysql = require('mysql');

const con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  let sql = "INSERT INTO qualification (degreeName, domain) VALUES ?";
  let values = [
    ['B', 'p'],
    ['A', 'q'],
    ...
  ]; //this is dynamic value that you can create
  con.query(sql, [values], function (err, result) {
    if (err) throw err;
    console.log("Number of records inserted: " + result.affectedRows);
  });
});

To generate the tuples (values) from the dataset (assumes that data is going be in that format):

const payload = {
  qualification: [
    { degreeName: "B", domain: "p" },
    { degreeName: "A", domain: "q" }
  ]
};
const tuples = payload.qualification.map(obj => [obj.degreeName, obj.domain]);

Which OPs something like this:

[ [ 'B', 'p' ], [ 'A', 'q' ] ]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! It worked. You exactly got what I wanted to say.
@SwapnilNakade Great. Happy to help! if the solution resolved you issue please mark it as accepted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.