Node js MySQL Select Query Example

In this post, we will see how to select a record from the MySQL database using Node js.

Setup MySQL database

Make sure that you have installed the MySQL database in your machine.
Use the following command to create a database:
create database demo;
Use below SQL script to create todos table in 'demo' database:
CREATE TABLE `todos` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `description` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;

Install MySQL Driver

To download and install the "mysql" module, open the Command Terminal and execute the following:
$npm install mysql --save
Now you have downloaded and installed a MySQL database driver.
Node.js can use this module to manipulate the MySQL database:
var mysql = require('mysql');

Node js MySQL Select Query Example

Use this example to insert records into a database. Let's create a file named 'read-record.js' and add the following code to it:
const mysql = require('mysql');
// connection configurations
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'demo'
});

// connect to database
connection.connect(function (err) {
    if (err) throw err
    console.log('You are now connected with mysql database...')
});

// Retrieve and return all todos from the database.

connection.query('select * from todos',
    function (error, results, fields) {
        if (error) throw error;
        console.log(JSON.stringify(results));
    });
Run above code with the following command:
$ node .\read-record.js
You are now connected with mysql database...
[{"id":2,"name":"Learn Advanced Express.js ","description":"Learn Advanced Express.js with examples"},{"id":3,"name":"Todo 2","description":"Todo 2 description"},{"id":5,"name":"Todo 1","description":"Todo 1 description"}]

References


Comments