How to connect MySQL database in Node.js
In this article, you will learn how to connect MySQL database in Node.js. Today we will show you how to connect a database and in the next article, you will learn how to integrate it with API.
Checkout more articles on Node.js
Steps to connect MySQL database in Node.js
1. Create a Node.js project
Run the following command to create a Node.js project and initialize it.
1 | npm init |
2. Install package
Let’s install mysql package using the following command.
1 | npm i mysql |
3. Create a connection and query the data
Import the mysql
and create a connection using the createConnection
function where you have to pass the host
, user
, password
, and database
.
1 2 3 4 5 6 7 8 | var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'demo' }); |
Now let’s get the data using the query.
1 2 3 4 5 6 7 8 9 | connection.connect(); connection.query('SELECT * FROM users', function (err, result, fields) { if (err) throw err; console.log(result); }); connection.end(); |
4. Output
Let’s put all the code together and see how it looks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'demo' }); connection.connect(); connection.query('SELECT * FROM users', function (err, result, fields) { if (err) throw err; console.log(result); }); connection.end(); |
Run the server.js
file using the following command.
1 | node server.js |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂