How to Connect to MySQL Database from Node.Js

In this article you will learn how to connect to MySQL server database using Node Js MySQL driver. We gonna use a MySQL driver called “mysql”. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.

MySQL is the most popular database system used with other programming languages like PHP,Java..etc. MySQL is ideal for both small and large applications. Which is developed distributed, and supported by Oracle Corporation. MySQL is very fast, reliable, free to download and use.

Installing node-mysql

Install node mysql driver with npm as shown below

Database Table and sample data

For this tutorial we will be using a database called “mysql-demo” and a table called todos. Here is a dump of the database, so that you can get up and running quickly

Sample code to get started.

Let’s create a file called app.js and import MySQL driver into that page. You can establish connection to mysql in two different methods, first on is basic connection method which is suitable for development and testing, second one is suitable for production which uses connection pooling. Connection pooling is a technique to maintain cache of database connection so that connection can be reused after releasing it. Basic version may not work for the concurrent users that is why pooling connection is preferred which can handle thousands of concurrent users.

Simple connection

Pooled connection

Then use the following command to run the code

Executing Queries – Reading, Creating, Updating, Destroying

As shown above, once the connection is established we will use the connection variable to execute a query against the database table(s).

In order to avoid SQL Injection attacks, you should always escape any user provided data before using it inside a SQL query. You can do so using the mysql.escape(), connection.escape() or pool.escape() methods. If you build your likes using wildcards like we did above you don’t have to use escape methods MySQL driver module will take of it.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

I am Arjun from Hyderabad (India). I have been working as a PHP Developer from last 6+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.