Languages
[Edit]
EN

Node.js - MySQL WHERE clause

0 points
Created by:
Geospatial-Palus
660

In this article, we would like to show you how to use SQL WHERE clause in Node.js.

Note: at the end of this article you can find database preparation SQL queries, you will also find an example of a more parameterized query there.

const mysql = require('mysql');

const connection = mysql.createConnection({             // gets connection with database
    host: 'localhost',  // '127.0.0.1'
    user: 'root',
    password: 'password',
    database: 'my_database',
});

connection.connect((error) => {
    if (error) throw error;
    const query = 'SELECT * ' + 
                  'FROM `users` ' +
                  'WHERE `name` = ?';
    const value = ['Chris'];              // SELECT * FROM `users` WHERE `name` = 'Chris'

    connection.query(query, value, (error, result) => { // sends queries and receives results
        connection.end();                               // closes connection
        if (error) throw error;
        console.log(result);
    });
});

Result: 

[{ id: 2, name: 'Chris', role: 'moderator' }]

Multiple conditions example:

const mysql = require('mysql');

const connection = mysql.createConnection({              // gets connection with database
    host: 'localhost', //  '127.0.0.1'
    user: 'root',
    password: 'password',
    database: 'my_database',
});

connection.connect(error => {
    if (error) throw error;
    const query = `SELECT * 
                   FROM ??
                   WHERE ?? = ?
                   OR ?? = ?`;
    const value = ['users', 'name', 'Chris', 'role', 'admin'];
    

    connection.query(query, value, (error, result) => {  // sends queries and receives results
        connection.end();                                // closes connection
        if (error) throw error;
        console.log(connection.sql);           // SELECT *
    });                                        // FROM `users`
});                                            // WHERE `name` = 'Chris'
                                               // OR `role` = 'admin'

Result: 

[
    { id: 1, name: 'John', role: 'admin' },
    { id: 2, name: 'Chris', role: 'moderator' }
]

Database preparation

create_tables.sql file:

CREATE TABLE `users` (
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(100) NOT NULL,
	`role` VARCHAR(15) NOT NULL,
	PRIMARY KEY (`id`)
)
ENGINE=InnoDB;

insert_data.sql file:

INSERT INTO `users`
	(`name`, `role`)
VALUES
	('John', 'admin'),
	('Chris', 'moderator'),
	('Kate', 'user'),
	('Denis', 'moderator');

More parameterized query

// ...
connection.connect(error => {
    if (error) throw error;
    const query = `SELECT * 
                   FROM ??
                   WHERE ?? = ?`;
    const value = ['users', 'name', 'Chris'];  // SELECT * FROM `users` WHERE `name` = 'Chris'

    connection.query(query, value, (error, result) => {  // sends queries and receives results
        connection.end();                                // closes connection
        if (error) throw error;
        console.log(result);
    });
});

The names of columns and tables can be placed in the query by a double question mark ??.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - MySQL

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join