How to Fetch (Select) Data From MySQL Database Using Node JS

How to Fetch (Select) Data From MySQL Database Using Node JS

Here you will learn how to Fetch or Select Data from MySQL Database Using Node JS. To Insert Fetch or Select Data from MySQL Database, we will use the mysql2 module.

But, before going further, I suggest you first check out this –


Database Configuration

Database Nametest
Table Nameusers

So first, Strat your MySQL Server and create a Database called test, and then inside the test database create a table called users.

Use the following SQL Code to create users table and the structure of the users table.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
 `age` int(11) NOT NULL,
 `email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Database Connection


const mysql = require('mysql2');
const db_connection = mysql.createPool({
    host: 'localhost',
    user: 'root',
    database: 'test',
    password:'your_db_password'
});

Fetch or Select Data From MySQL Database

db_connection.promise()
.execute("SELECT * FROM `users`")
.then(([rows]) => {
    // show the first user name
    console.log(rows[0].name);
    // show the all users name
    rows.forEach(user => {
        console.log(user.name);
    });
}).catch(err => {
    console.log(err);
});
db_connection.promise()
.execute("SELECT * FROM `users` WHERE `id`=?",[1])
.then(([rows]) => {
    // show the first user name
    console.log(rows[0].name);
   // show the first user email
    console.log(rows[0].email);
}).catch(err => {
    console.log(err);
});

Full Code of Fetch Data


const mysql = require('mysql2');
const db_connection = mysql.createPool({
    host: 'localhost',
    user: 'root',
    database: 'test',
    password:'your_db_password'
});

db_connection.promise()
.execute("SELECT * FROM `users`")
.then(([rows]) => {
    // show the first user name
    console.log(rows[0].name);
    // show the all users name
    rows.forEach(user => {
        console.log(user.name);
    });
}).catch(err => {
    console.log(err);
});

Leave a Reply

Your email address will not be published. Required fields are marked *