Installing and setting mysql with nodejs in ubuntu


Nodejs has seen dramatic increase in adoption in the backend side since it allows javascript usage in backend along with frontend. It is usually advisable to use nosql databases like mongodb,couchbase and aerospike but there might be a need to use mysql databases with nodejs until you successfully migrate your mysql dbs to nosql stack.

In today’s tutorial we are going to install mysql in ubuntu and create basic connection of nodejs with mysql database using express framework.

Lets get started :

Install mysql on ubuntu:

During installation you will be asked to set up root password.Make sure you keep a note of root password since we are going to require that password in the later part of the tutorial.

Check your mysql version with the following command:

You will see output like this:

Check for version after Distrib. If it is less than 5.7.6 you should initialize the data directory by running:

Then check mysql service status by running following command:

If it shows status: Unknown job: mysql then start mysql service by running the following command:

Now login into mysql cli with the following command:

It will ask for root password which you set up during mysql installation.

Now you will get access to mysql cli. Run the following command to create database in mysql:

Replace dbname with database name of your choice.

In order to verify that database has been created run the following command:

Exit mysql cli using command ctrl+c.

Now create a new folder in Documents for your node project.

Run the following command to initialize npm in the folder.

Now install express and mysql npm modules.

Now create server.js and paste the following code to test your installation.

Replace password value with mysql root user password and dbname with database name you created earlier.

Now if you have nodemon install run the following command to check your database connection:

If you get log as Database is connected in terminal logs then your nodejs setup with mysql is complete.That’s it for today’s tutorial.In the next tutorial I will cover how to handle user registration and login using same stack.

Connect Deeper

Kindly mention your feedback in the comments and follow our facebook page to get notified about similar posts in the future here:Technoetics

Share post-
About Saurabh Mhatre 70 Articles
Currently working in web and hybrid application development