0

I want to insert each element from an array as the rows of a column.

Example:

array = [1,2,3,2];

the result will be:

column1 | 
---------
    1   |  
    2   |  
    3   |  
    2   |  

I tried out the following code below in my Node.js file but it doesn't seem to work.

var array = [1,2,3,2]; 

var queryString = "INSERT INTO table (column1) VALUES ((${array.map((v,i) => `${i+1}`).join(',')}) RETURNING *";

    db.query(queryString, array, (err, result) => {
        if (err) throw err;
    });

1 Answer 1

1

I would rather use a package like sqlstring to ease the query creation and prevent nasty SQL injections. In any case the resulting SQL query should look like;

INSERT INTO table (column1) VALUES (1), (2), (3), (2);

const numbers = [1, 2, 3, 2];
const values = numbers.map (x => `(${x})`).join (', ');
const query = `INSERT INTO table (column1) VALUES ${values};`;
Sign up to request clarification or add additional context in comments.

1 Comment

How do I do the same for update? Do I need a forEach loop?

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.