Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"where in" MySQL query in nodejs

I need to make MySQL query using "WHERE IN". This is my query:

var myQuery = 'SELECT uid FROM ' +tableName+ ' where Gender IN (' + Info.Gender.join() + ')';

If i print Info.Gender it will be ['Male', 'Female'], as a string. but when the query is done it says

SELECT uid FROM appUsers where Gender IN (Male, Female)

But should be:

SELECT uid FROM appUsers where Gender IN ('Male', 'Female')

That means it takes the Female not as a string.

Any ideas?

like image 406
daniel the man Avatar asked Dec 16 '15 10:12

daniel the man


People also ask

How do I run a SQL query in node JS?

Step 1, install the NPM package called sqlite3 (Read the sqlite3 docs here). sqlite3 helps you to connect to your SQLite database and to run queries. Step 2, In your the JS file where you want to run the SQLs, import/require sqlite3 and fs (No, you don't need to install this one. It comes with NodeJS).

Can I use MySQL in NodeJS?

Once you have MySQL up and running on your computer, you can access it by using Node.js. To access a MySQL database with Node.js, you need a MySQL driver.

How do I connect to a node in MySQL?

const connection = mysql. createConnection({ host: 'localhost', // host for connection port: 3306, // default port for mysql is 3306 database: 'test', // database from which we want to connect out node application user: 'root', // username of the mysql connection password: 'root' // password of the mysql connection });


2 Answers

You should use query escaping (provided that you're using node-mysql):

var myQuery = 'SELECT uid FROM ?? where Gender IN (?)';
connection.query(myQuery, [ tableName, Info.Gender ], ...);
like image 170
robertklep Avatar answered Oct 01 '22 20:10

robertklep


You need single quotes in your query:

var myQuery = "SELECT uid FROM " +tableName+ " where Gender IN ('" + Info.Gender.join("','") + "')";
like image 29
Clay Avatar answered Oct 01 '22 18:10

Clay