Clue Mediator

How to connect MySQL database in Node.js

📅February 16, 2022

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
  2. Install package
  3. Create a connection and query the data
  4. Output

1. Create a Node.js project

Run the following command to create a Node.js project and initialize it.

npm init

2. Install package

Let’s install mysql package using the following command.

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`.

var mysql = require('mysql');

var connection = mysql.createConnection({
	host: 'localhost',
	user: 'root',
	password: '',
	database: 'demo'
});

Now let’s get the data using the query.

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.

server.js

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.

node server.js

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂