0

i have a problem. I have an array and i want that each element to be a row from column;

Example:

My Array: const myArray = ['A', 'B', 'C', 'D'];

and result is:

Column1 | 
-----------------------------------------
    A   |  
    B   |  
    C   |  
    D   |  

I am using Node.js with library node-postgres:

var queryString = "INSERT INTO test (id) VALUES (" + "'" + [myArray] + "'" + ") RETURNING *";

pool.connect((err, client, done) => {
  if (err) {
    done();
    console.log(err)
    return res.status(500).json({
      success: false,
      data: err
    })
  }
  client.query(queryString, (err, result) => {
    done();
  });
})

But it goes like a bigger string;

Someone could help me?

2 Answers 2

2

I think this is what you're looking for:

var queryString = `INSERT INTO test (id) VALUES ("${myArray.join('"),("')}") RETURNING *`

i.e.

INSERT INTO test (id) VALUES (("A"),("B"),("C"),("D")) RETURNING *

A better solution would be to use query parameters:

var queryString = `INSERT INTO test (id) VALUES (${myArray.map((v,i) => `$${i+1}`).join('),(')}) RETURNING *`

i.e.

INSERT INTO test (id) VALUES (($1),($2),($3),($4)) RETURNING *

And then use it like:

client.query(queryString, myArray, (err, result) => {
  done();
});
Sign up to request clarification or add additional context in comments.

4 Comments

Hello, same thing still :(
@muistooshort Yes, you're right - query parameters would be a better solution - I updated my answer
Or ${myArray.map((v,i) => `($${i+1})`).join(',')} if ('),(') looks like it is staring at you ;)
I have corrected it to what the correct SQL should contain. The insert pairs all should be additionally wrapped by () for the whole set.
0

Well! I am sure this should have been asked somewhere. but whatever.. ..you should have a code look like the following. - by simply add multiple inserted values as nested array. :

    var queryString = "INSERT INTO test (id) VALUES ($1) RETURNING *";
    var values = [['A'],['B'],['C'],['D']]

and when you come to the client query

   client.query(queryString, values, (err, result) => ...

Comments

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.