How To Connect Nodejs Application To MySQL Database

In this article, we will discuss how to connect Node.js with MySQL to build database-driven applications. To connect Node.js with MySQL to build database-driven applications we follow these steps

  • Step 1: Install MySQL and MySQL module for Node.js
  • Step 2: Create a MySQL database and table
  • Step 3: Connect Node.js with MySQL
  • Step 4: Perform CRUD operations

Step 1: Install MySQL and MySQL module for Node.js

The first step is to install MySQL and the MySQL module for Node.js. You can install MySQL using your package manager or download it from the official website. Once MySQL is installed, you can install the MySQL module for Node.js using the following command:

npm install mysql 

Step 2: Create a MySQL database and table

Before connecting Node.js with MySQL, you need to create a MySQL database and table to store data. You can use the following SQL commands to create a database and table:

CREATE DATABASE mydb;
USE mydb;
CREATE TABLE users (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  email VARCHAR(50) NOT NULL,
  PRIMARY KEY (id)
);

Step 3: Connect Node.js with MySQL

To connect Node.js with MySQL, you need to create a connection object using the mysql module. The connection object contains the necessary information to connect to the MySQL database.

Here’s an example of how to create a connection object:

const mysql = require('mysql');
 
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'mydb'
});
 
connection.connect((error) => {
  if (error) throw error;
  console.log('Connected to MySQL database!');
});

In this example, we create a connection object with the host, user, password, and database properties. We then call the connect() method on the connection object to establish a connection to the MySQL database.

Step 4: Perform CRUD operations

Once you have established a connection to the MySQL database, you can perform CRUD (Create, Read, Update, Delete) operations on the database using Node.js.

Here’s an example of how to insert data into the users table:

const user = { name: 'John Doe', email: 'john.doe@example.com' };
connection.query('INSERT INTO users SET ?', user, (error, results) => {
  if (error) throw error;
  console.log('User inserted successfully!');
});

In this example, we create a user object with name and email properties. We then use the query() method on the connection object to insert the user object into the users table.

Happy Coding !!!
#nodejs #mysql 

How To Connect Nodejs Application To MySQL Database
4.05 GEEK