
Home in NodeJs
Using SELECT * FROM
in MySQL with Node.js is the most common way to fetch data from a table. Here's how to do it the right way 👇
✅ Step 1: Install MySQL Package
npm install mysql const mysql = require('mysql');const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase'});connection.connect();const sql = 'SELECT * FROM users';connection.query(sql, (err, results) => { const mysql = require('mysql2/promise');async function getUsers() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase' }); const [rows] = await connection.execute('SELECT * FROM users'); console.table(rows); await connection.end();}getUsers();
🔍 Select Specific Columns
SELECT name, age FROM users;
const sql = 'SELECT name, age FROM users';
🧠 Combine with WHERE, ORDER, LIMIT
SELECT * FROM users WHERE age > 25 ORDER BY name LIMIT 2;
const sql = 'SELECT * FROM users WHERE age > ? ORDER BY name LIMIT ?';const values = [25, 2];connection.query(sql, values, (err, results) => { if (err) throw err; console.table(results);});