Node.js MySQL: Select Records Example
Retrieving data from a MySQL database in Node.js is simple with the mysql package. This example shows you how to connect and run a basic SELECT query.
Node.js Tutorial:-
SQL Tutorial:-
Install the MySQL Package
npm install mysql
Example: Select All Employees
Create a file named select.js inside a folder called DBexample:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345",
database: "updategadh"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM employees", function (err, result) {
if (err) throw err;
console.log(result);
});
});
Run the Script
node select.js
The script connects to MySQL and prints all rows from the employees table to the terminal.
SELECT Specific Columns
con.query("SELECT name, salary FROM employees", function (err, result) {
if (err) throw err;
result.forEach(row => console.log(`${row.name}: ${row.salary}`));
});
SELECT with WHERE (Parameterized)
Always use parameters to avoid SQL injection:
const city = "Mumbai";
con.query("SELECT * FROM employees WHERE city = ?", [city], function (err, result) {
if (err) throw err;
console.log(result);
});
Download New Real Time Projects:- Click here
Complete Advance AI topics:-
Conclusion
Selecting data from MySQL in Node.js takes only a few lines. Use parameterized queries for security, and explore mysql2 or sequelize for production apps. For more tutorials, stay tuned to .
node js mysql select records w3schools
node js mysql select example
node js mysql query return result
nodejs mysql query with parameters
connect mysql with node js express
nodejs mysql crud
nodejs mysql connection pool
node.js mysql select query example