EN
Node.js - MySQL WHERE clause
0 points
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.
xxxxxxxxxx
1
const mysql = require('mysql');
2
3
const connection = mysql.createConnection({ // gets connection with database
4
host: 'localhost', // '127.0.0.1'
5
user: 'root',
6
password: 'password',
7
database: 'my_database',
8
});
9
10
connection.connect((error) => {
11
if (error) throw error;
12
const query = 'SELECT * ' +
13
'FROM `users` ' +
14
'WHERE `name` = ?';
15
const value = ['Chris']; // SELECT * FROM `users` WHERE `name` = 'Chris'
16
17
connection.query(query, value, (error, result) => { // sends queries and receives results
18
connection.end(); // closes connection
19
if (error) throw error;
20
console.log(result);
21
});
22
});
23
Result:
xxxxxxxxxx
1
[{ id: 2, name: 'Chris', role: 'moderator' }]
xxxxxxxxxx
1
const mysql = require('mysql');
2
3
const connection = mysql.createConnection({ // gets connection with database
4
host: 'localhost', // '127.0.0.1'
5
user: 'root',
6
password: 'password',
7
database: 'my_database',
8
});
9
10
connection.connect(error => {
11
if (error) throw error;
12
const query = `SELECT *
13
FROM ??
14
WHERE ?? = ?
15
OR ?? = ?`;
16
const value = ['users', 'name', 'Chris', 'role', 'admin'];
17
18
19
connection.query(query, value, (error, result) => { // sends queries and receives results
20
connection.end(); // closes connection
21
if (error) throw error;
22
console.log(connection.sql); // SELECT *
23
}); // FROM `users`
24
}); // WHERE `name` = 'Chris'
25
// OR `role` = 'admin'
Result:
xxxxxxxxxx
1
[
2
{ id: 1, name: 'John', role: 'admin' },
3
{ id: 2, name: 'Chris', role: 'moderator' }
4
]
create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE `users` (
2
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
3
`name` VARCHAR(100) NOT NULL,
4
`role` VARCHAR(15) NOT NULL,
5
PRIMARY KEY (`id`)
6
)
7
ENGINE=InnoDB;
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO `users`
2
(`name`, `role`)
3
VALUES
4
('John', 'admin'),
5
('Chris', 'moderator'),
6
('Kate', 'user'),
7
('Denis', 'moderator');
xxxxxxxxxx
1
// ...
2
connection.connect(error => {
3
if (error) throw error;
4
const query = `SELECT *
5
FROM ??
6
WHERE ?? = ?`;
7
const value = ['users', 'name', 'Chris']; // SELECT * FROM `users` WHERE `name` = 'Chris'
8
9
connection.query(query, value, (error, result) => { // sends queries and receives results
10
connection.end(); // closes connection
11
if (error) throw error;
12
console.log(result);
13
});
14
});
15
The names of columns and tables can be placed in the query by a double question mark ??
.