Retrieving MySQL Data using Node.js: A Practical Guide to `SELECT` Statements

Learn how to query and retrieve data from MySQL databases using Node.js. This tutorial provides a step-by-step guide with code examples, demonstrating how to execute `SELECT` statements, handle the results, and connect to your MySQL database, enabling efficient data retrieval in your Node.js applications.



Node.js MySQL Select Records

This section demonstrates how to retrieve data from a MySQL table using Node.js. The `SELECT` statement is the core command for querying data.

Retrieving All Records from a Table

Let's retrieve all data from the "employees" table. Create a file named `select.js` with the following code:

Selecting All Records

var mysql = require('mysql');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "12345", // Replace with your MySQL root password
    database: "tutorialsarena" // Replace with your database name
});

con.connect(function(err) {
    if (err) throw err;
    con.query("SELECT * FROM employees", function (err, result) {
        if (err) throw err;
        console.log(result);
    });
});
            

Remember to replace `"12345"` with your MySQL root password and `"tutorialsarena"` with your database name. Run this using `node select.js`. The output will be an array containing all rows from the `employees` table.

The same query can also be executed directly in a MySQL client using:

MySQL Client Query

SELECT * FROM employees;
            

next →

← prev