Node.js Connect Mysql with Node app

Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications. In this article, we’ll explore how to connect a Node.js application with a MySQL database, covering the necessary setup, configuration, and basic CRUD (Create, Read, Update, Delete) operations.

Prerequisites:

  • Node.js: Download and install from nodejs.org.
  • MySQL: Download and install from mysql.com.
  • MySQL Workbench (optional): A GUI tool for MySQL, helpful for database management

Important Points

  • NodeJs: An open-source platform for executing javascript code on the server side. Also a javascript runtime built on Chrome’s V8 JavaScript engine.
  • Mysql: An open-source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). It is the most popular language for adding, accessing and managing content in a database. Here we will use the Mysql as a database for our node application.
  • Node -v: It will show node version in our system.
  • Mysql -v: It will show Mysql version in our system.

Create a New Node.js Project

Step 1: Open your terminal and create a new directory for your project.

mkdir node-mysql-app
cd node-mysql-app

Step 2: Initialize a new Node.js project:

npm init -y

Step 3: Install MySQL Package

Install the mysql package, which is a Node.js driver for MySQL:

npm install mysql

Step 4: The updated dependencies in package.json file will look like

Step 5: Database Connection

Create a Javascript file named server.js in the root of the project folder. Code for creating connection is as given below:

Run the file server.js with following command as:

node server.js

Conclusion

Connecting Node.js with MySQL is straightforward and powerful, enabling developers to build data-driven applications with ease. By following the steps outlined in this article, you can set up a basic Node.js application that interacts with a MySQL database, performing essential CRUD operations. This foundation can be expanded to suit more complex application requirements, including advanced querying, data validation, and secure authentication.


Contact Us