Node.js Connect MySQL Database with Example
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
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.connect();
connection.query('SELECT * FROM users', function(err, result, fields)
{
if (err) throw err;
console.log(result);
});
connection.end();
Now we have to run this file by typing this command:
node server.js
Output:

I hope this article will help you. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)