Node.js Connect MySQL Database with Example

Published on April 14, 2019 49 sec read

We can easily connect to the MySQL database in Node.js. Node.js have a driver for MySQL. If you are very beginners in Node.js, please read this article first Build a Simple Node.js Web Server for Beginners

Table of Contents

  1. Install MySQL
  2. Create a Database
  3. Create & Run server.js File

Step 1 : Install MySQL

Navigate to your project folder and run this command to install MySQL:

npm install mysql

After successfully installation, you will see mysql folder under node_modules directory.

Step 2 : Create a Database

Let’s create a database named ‘test‘ and create a table named ‘users‘. After creating test database, you can run this SQL to create users table:

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Now import sample data to users table:

INSERT INTO `users` (`id`, `name`) VALUES
(1, 'Md Obydullah'),
(2, 'Md Najmul Hasan'),
(3, 'Md Mehadi Hasan');

Step 3 : Create & Run server.js File

Let’s create a js file named ‘server.js’ and paste this code:

var mysql      = require('mysql');

var connection = mysql.createConnection({ 
  host     : 'localhost', 
  user     : 'root', 
  password : '', 
  database : 'test' 


connection.query('SELECT * FROM users', function(err, result, fields)  
  if (err) throw err;


Now we have to run this file by typing this command:

node server.js


I hope this article will help you. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.