Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

node.js SQL Insert Into with array

I'm new to Node.js and I've hit a roadblock I can't figure out. I'm trying to add an array to a SQL table using an INSERT INTO query. Following the example [here][1] I see that I add a question mark as a placeholder for my values array, and the code takes care of the rest - but that doesn't seem to be working.

Here's the code:

var temp = [1,3,2];
conn2string= "INSERT INTO " + process.env.DB_TABLE + '(`0`, `1`, `2`) VALUES ? ';

let query = connection.query(conn2string, temp, function (err, result) { // this will insert in to data base  //[vals2[0]]

And the resulting SQL connection string is:

'INSERT INTO test(`0`, `1`, `2`) VALUES 1 `

What I'm expecting Is:

'INSERT INTO test(`0`, `1`, `2`) VALUES (1, 3, 2); `

Any suggestions what I'm doing wrong?


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

1 Answer

0 votes
by (71.8m points)

To do this with the mysql package, you need to wrap the temp variable inside an array. Remember to add the parentheses around the ? of the VALUES.

var temp = [1, 3, 2];
conn2string =
  "INSERT INTO " + process.env.DB_TABLE + "(`0`, `1`, `2`) VALUES (?) ";

let query = connection.query(conn2string, [temp], function (err, result) {
  
});

This is because the parameter after the SQL string expects an array whose elements match each ? or ?? in the SQL string. By passing the temp array directly, you're essentially telling it that the first ? is 1, the second ? is 3, the third ? is 2. However, when you wrap the temp array in another array, you're essentially telling it that the value of the first ? is the temp array, and it formats it accordingly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...