It’s very easy to use MySQL with Node.js. This tutorial will explain how to connect the MySQL server database using Node.js. 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.

connect-mysql-database-using-node.js

Connect MySQL Database using Node.js

First, you need to install mysql driver with the help of node package manager. Use the following command on the terminal or node shell.

Database Configuration

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,

Get strated with Code

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.

Pooled connection

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.

Run the following command in shell

Execute the Queries

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

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.