Node.js MySQL Connect to DATABASE

Learn to Connect to MySQL database in Node.js using mysql.createConnection method with an example Node.js program.

Node.js MySQL Connect to a database

Node.js provides a module to connect to MySQL database and perform MySQL operations.

connect to MySQL database in Node.js

Following is a step-by-step guide to connect to MySQL database with an example.

  • Step 1 : Make sure that MySQL is configured properly. Collect the information about IP Address, User Name and Password.
  • Step 2 : In your node.js program, include mysql module.
    MySQL module has to be installed before it can be used. Otherwise you would get an error.
    To install mysql module, refer how to install MySQL in Node.js.
  • Step 3 : Create a connection variable with IP Address, User Name and Password collected in step 1.
  • Step 4 : Make a call to connect function using connection variable, that we created in the previous step.
    Function provided as argument to connect is a callback function. After node.js has tried with connecting to MySQL Database, the callback function is called with the resulting information sent as argument to the callback function.


Example program to connect to MySQL database in Node.js


Conclusion :

In this Node.js TutorialNode.js MySQL – Connect to Database, we have learnt to Connect to MySQL database using Node.js MySQL Module -> createConnection method with the help of an example Node.js program.