Select Page

Hey devs, here is a new article. During the days I was off, I was working on a project. For this project, I worked on both the backend and the frontend. I know how to create a backend, but I’m not as good as working on the frontend, so a few things were a bit challenging for me. However, I managed to create a working backend. In this article I will explain how I connect a mySQL database in node.js.

I got the idea for this article while I was doing the project!

First and foremost, in order to start this tutorial you need a mySQL database. I won’t go into details on how you can create one, because this article focuses on something else.

After you create a database, you need some information that we will use in our backend, like the ‘password’, ‘user’, ‘database’ and ‘host’. If you don’t have this info, you can’t connect your database to the backend.

After you get all the info you need, you can start this tutorial. In order to connect the database, you need to install mysql in your node.js project:

npm i mysql

And you have to import it in your file:

var mysql = require("mysql");

When I have to use a database in node.js, I usually have the database open at the same time, so you can test if the code works. I usually use sequelpro. In order to open the database, you will need the same information we’ll use in our code. In the next part of the code, there is an example on how I usually connect a mySQL database in node.js:

var mysqlDB = mysql.createPool({
    host: "host",
    user: "user",
    password: "password",
    database: "database",
    queryFormat: (query, values) => {
        if (!values) return query;
        return query.replace(/\:(\w+)/g, function (txt, key) {
            if (values.hasOwnProperty(key)) {
                return mysql.escape(values[key]);
            }
            return txt;
        });
    }
});

The information you will use in the backend can’t be in this file. I usually save them in the .env file and then import them.

Check other posts