Introduction
This is another article where the main focus still has a relation with the previous article. The previous article has the title of ‘How to Connect to MySQL Database Server from a NodeJS Application’ in this link. It is performing on how to connect to a MySQL Database Server from a NodeJS application. In the previous article, the connection to a MySQL Database Server is possible only with ‘mysql’ module.
But in this article, the connection to a MySQL Database Server is available with the help of another module with the name of ‘sequelize’. The example is using just a simple NodeJS application. It is a simple one just to show how to connect to the MySQL Database Server.
Connect to MySQL Database Server using Sequelize Module
So, in order to achieve it, the following is the step to do it :
-
First of all, make sure that the tool for developing NodeJS application is available. Read articles about how to install the npm tool. For an example, the article with the title of ‘How to install npm’ in this link. Another is an article with the title of ‘How to Install npm in Ubuntu Linux operating system’ in this link.
-
Next, make sure to choose a folder to put all the files for storing the NodeJS application script. For an example, in this article ‘/home/admin/nodejs/db’.
-
After that, just create a new file with the name of ‘app.js’ for an example as follows :
const sequelize = require("sequelize"); const db = new sequelize("db_master","db_user","password",{ host: "10.0.2.2", dialect: "mysql" }); db.authenticate().then(() => console.log("Connected to the database !") );
Just change the above setting accordingly. The following is the pattern from the above line of codes for defining a constant with the name of ‘db’. That constant will act as a container to store the instance of ‘sequelize’. So, the instantiation pattern exist as follows :
const db = new sequelize("db_name","db_user","db_user_password",{ host: "db_server_ip_address", dialect: "mysql" });
Make sure all of the parameter is correct according to the environment of the MySQL server database.
-
Do not forget to install the necessary module. In the NodeJS script above, it need ‘express’ and ‘mysql’ NodeJS module. Just check the article with the title of ‘How to Install MySQL Module in NodeJS Application’ in this link about how to install ‘mysql’ module. Furthermore, another article with the title of ‘How to Install Express Module in NodeJS Application’ in this link for installing ‘express’ module.
-
Test the connection to the MySQL Database Server first.
-
Last but not least, execute the NodeJS application as follows using :
[admin@10 db]$ node db-connect-sequelize.js Executing (default): SELECT 1+1 AS result Connected !
- If it fails because of the access privilege, just read the article with the title of ‘How to Solve Error Message ER_DBACCESS_DENIED_ERROR: Access denied for user ‘db_user’@’%’ to database ‘db_master” in this link.