How to Connect to MySQL Database in Node.Js

Spread the love

In this article you will figure out how to associate with MySQL server database utilizing Node Js MySQL driver. We going to utilize a MySQL driver called “mysql”. It is composed in JavaScript, does not require gathering, and is 100% MIT authorized.

MySQL is the most mainstream database framework utilized with other programming dialects like PHP,Java..etc. MySQL is perfect for both little and huge applications. Which is produced appropriated, and upheld by Oracle Corporation. MySQL is quick, dependable, allowed to download and utilize.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *