Connect to database (MySQL) in nodejs

Tram Ho


Hello friends, I have come back, continuing with the series about Nodejs cơ bản , in this article I will introduce to everyone how to install and connect mysql to nodejs.


Install mysql

To connect to mysql, we must have mysql correct. You can install workbench

Or install mysql directly in the terminal like me: v. Because this article mainly talks about connecting mysql in Nodejs , I would like to show you how to install mysql on ubuntu only: v

  • First, you need to update the apt package with the command

  • next is installing Mysql

  • Next is running the command

To increase the security of mysql more, I am not sure if you know this, please comment below for me to add. You guys just press y until it is All done! is to be

  • Next login with root you run the command

then run to the next command

Where your_password is the pass you want to set.

OK now try running the command

Then enter the password just changed at the top to see, run the next command

This is ok. Next we will create a database to connect to Nodejs . Simply run this command

is created a new db: v. Note that dbTest here is the name of the database. You can refer to the command manipulation with mysql here .

Connect mysql to Nodejs

To connect to mysql, we need to install the MYSQL module as we did in the previous posts to install a module we just need to run the command.

Next in the index.js file we will require mysql module. Make the declaration on the connection as follows:

The first is to declare host, user, password (if any), database name, type unicode. Next is the connect function here, I make the connection. If there is an error, print the error or else it will log connect success .

Create Table

As you know, the previous articles I used arrays to store data so when pressing f5 again will lose the newly added records, but in today’s post, we have connected to the database. then that is not a problem anymore. Now we will create a posts table to replace the Mảng posts that we used to in previous posts. First, I will declare a sql statement as follows:

create a posts table with 2 fields of id int, auto increment, primary key, and title field has varchar data type. Next just need to trace the function to run the other sql.

Create table success on the terminal shows that the Create table success has been created successfully


So in this article I have introduced to you how to install mysql on ubuntu and how to connect mysql to nodejs . In the next post, I will perform the functions of data editing, edit delete table, and edit new added functions in the previous post. The article is somewhat flawed, we hope you to comment below for more, if you find the article useful, give yourself an upvote. Click follow to be able to follow my latest posts. Again thank you !!!

Share the news now

Source : Viblo