Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array in Mysql query with nodejs

I have a simple query that I want to pass an array inside which has 5 items. I am using the mysql module so I know it can be done but am not doing the synatx right and therefore getting a syntax error.

Below is the query:

`UPDATE table1 SET table1.col=0 WHERE (table1.col2) IN = (?) AND table1.id=(SELECT ...);`,[arr]

//arr = [1,2,3,4,5];

I have tried:

`UPDATE table1 SET table1.col=0 WHERE (table1.col2) IN = (?,?,?,?,?) AND table1.id=(SELECT ...);`,[arr]`

but I still get a syntax error.

like image 593
John James Avatar asked Aug 27 '26 21:08

John James


1 Answers

Adding on to Bill Karwin's answer, you can also pass an array to the MySQL query against the '?' placeholder in the same way

WHERE table1.col2 IN (?)
//arr = [1,2,3,4,5];

Passing arr along with the query will convert it to the required SQL string. The mysql module uses the 'SqlString.arrayToList' function from 'sqlstring' module internally for the transformation: https://github.com/mysqljs/sqlstring/blob/8f193cae10a2208010102fd50f0b61e869e14dcb/lib/SqlString.js#L60

like image 138
Vedant Goenka Avatar answered Aug 29 '26 10:08

Vedant Goenka