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.

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.

2. Install package

Let’s install mysql package using the following command.

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.

Now let’s get the data using the query.

4. Output

Let’s put all the code together and see how it looks.

server.js

Run the server.js file using the following command.

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

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *