Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

mysql - Insert array as column in Node.js

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;
    });
question from:https://stackoverflow.com/questions/65880520/insert-array-as-column-in-node-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...